List IP all addresses in a subnet

Ray Womack picture Ray Womack · Jul 10, 2010 · Viewed 13.1k times · Source

I need to get all of the IP addresses contained in within a subnet and I'm trying to do it using IPnetwork

For example the subnet 192.168.1.0/29 would have the following output:

        // Output
        // 192.168.1.0
        // 192.168.1.1
        // 192.168.1.2
        // 192.168.1.3
        // 192.168.1.4
        // 192.168.1.5
        // 192.168.1.6
        // 192.168.1.7

Here is my code:

        IPNetwork ipn = IPNetwork.Parse("192.168.1.0/29");
        IPAddressCollection ips = IPNetwork.ListIPAddress(ipn);

        foreach (IPAddress ip in ips)
        {
            Console.WriteLine(ip);
        }

        // Output
        // 192.168.1.0
        // 192.168.1.0
        // 192.168.1.0
        // 192.168.1.0
        // 192.168.1.0
        // 192.168.1.0

As you can see, this is not the desired result. What am I missing? Is there another tool or method to get this job done? I have manage to hack something up, but it ain't pretty and I'm not sure if it's properly enumerating larger subnets.

Answer

LukeSkywalker picture LukeSkywalker · Jul 22, 2010

ipnetwork library has been updated (to version 1.3.1) with patch and a testunit covering this issue. It can be downloaded at IPnetwork