user2307236
user2307236

Reputation: 755

Find all the IP between the a first IP and a last IP

I am using IPNetwork C# library to find the first and last usable IP address. What I want to achieve is to print or store in a list all the range of IP addresses between the first and last usable IP. I am using the below to find the first and last usable IP.

    IPNetwork ipnetwork = IPNetwork.Parse("192.168.1.1/24");
    string first = ipnetwork.FirstUsable.ToString();
    string last = ipnetwork.LastUsable.ToString();

If I pass a net mask greater or equal to 24 it is quite straightforward to print all the range because with /24 at maximum we have 256 IP addresses, 254 available for the host and a simple loop will generate all the range because only the fourth octet will be changed. However if I pass a net mask less than \24 example \23 then the third octet needs to change as well and a simple loop will not do the job and another solution needs to be found. Also the parameter passed to IPNetwork.Parse might not be necessary 192.168.1.1 or 10.0.2.1 but 192.168.1.130 or 10.0.2.200 respectively which is something that needs to be considered as well.

Upvotes: 1

Views: 1571

Answers (1)

LukeSkywalker
LukeSkywalker

Reputation: 341

Example 8 :

IPNetwork net = IPNetwork.Parse("192.168.0.1/23");
IPNetwork ips= IPNetwork.Subnet(net , 32);

Console.WriteLine("{0} was subnetted into /{1} ips", net ,     ips.Count);
Console.WriteLine("First: {0}", subneted[0]);
Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]);
Console.WriteLine("All  :");

foreach (IPNetwork ipnetwork in ips)
{
    Console.WriteLine("{0}", ipnetwork);
}

Output

192.168.0.1/23 was subnetted into /32 subnets
First: 192.168.0.0/32
Last : 192.168.1.254/32
All  :
192.168.0.0
192.168.0.1
...
192.168.1.254

Have fun !

Upvotes: 1

Related Questions