Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there native .NET type for CIDR subnets?

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.

like image 313
Neil C. Obremski Avatar asked Nov 22 '08 00:11

Neil C. Obremski


People also ask

What is CIDR IP format?

CIDR (Classless Inter-Domain Routing) -- also known as supernetting -- is a method of assigning Internet Protocol (IP) addresses that improves the efficiency of address distribution and replaces the previous system based on Class A, Class B and Class C networks.

What is CIDR for subnet?

CIDR notation is really just shorthand for the subnet mask, and represents the number of bits available to the IP address. For instance, the /24 in 192.168. 0.101/24 is equivalent to the IP address 192.168. 0.101 and the subnet mask 255.255.

Is subnet mask and CIDR the same?

Subnet masks serve the same purpose as CIDR blocks, they are just formatted differently. Instead of an IP address followed by a one- or two-digit number, it is an IP address followed by four more numbers each separated by a decimal point (similar to a second IP address).


1 Answers

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
like image 73
Koen Zomers Avatar answered Oct 09 '22 14:10

Koen Zomers