Is there native .NET type for CIDR subnets?
Asked Answered
F

4

22

It's simple enough to code up a class to store/validate something like 192.168.0.0/16, but I was curious if a native type for this already existed in .NET? I would imagine it would work a lot like IPAddress:

CIDR subnet = CIDR.Parse("192.168.0.0/16");

Basically it just needs to make sure you're working with an IPv4 or IPv6 address and then that the number of bits your specifying is valid for that type.

Falsity answered 22/11, 2008 at 0:6 Comment(0)
T
4

No there is such native type in .NET, you will need to develop one your self.

Tisiphone answered 22/11, 2008 at 14:45 Comment(0)
M
30

You can use the code from GitHub to do just that:

https://github.com/lduchosal/ipnetwork

IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24");

Console.WriteLine("Network : {0}", ipnetwork.Network);
Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
Console.WriteLine("Usable : {0}", ipnetwork.Usable);
Console.WriteLine("Cidr : {0}", ipnetwork.Cidr);

Output

Network : 192.168.168.0
Netmask : 255.255.255.0
Broadcast : 192.168.168.255
FirstUsable : 192.168.168.1
LastUsable : 192.168.168.254
Usable : 254
Cidr : 24
Mcmillon answered 10/2, 2010 at 19:57 Comment(0)
F
14

For ASP.NET Core there is now IPNetwork class. Example usage below:

var addr = IPAddress.Parse("192.168.0.0");
var mask = 16;
var test = new IPNetwork(addr, mask).Contains(context.Connection.RemoteIpAddress);
Fiacre answered 29/7, 2020 at 19:55 Comment(0)
A
5

IPNetwork is now available in the System.Net namespace starting with .NET 8.

IPNetwork n = IPNetwork.Parse("192.168.0.0/16");
Adventitia answered 30/10, 2023 at 22:17 Comment(0)
T
4

No there is such native type in .NET, you will need to develop one your self.

Tisiphone answered 22/11, 2008 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.