Python CIDR Block Converter December 14th, 2007

I wrote a Python script that converts a CIDR Block into a list of individual IP addresses, one-per-line. I found that I needed to repeat some network-related tasks across an entire subnet, and this script provides an easy way to automate these kinds of tasks in a shell environment. The source code and sample usage for the script follow:

One item to note is a key difference between the way this program computes a CIDR block and others I have seen. The lazy way to convert a CIDR block to a list of IPs is to calculate the number of IP addresses in the subnet, (2^(32 – $subnetSize)), and simply increment the base IP address that number of times. This method is deficient because, as in the example usage above, the base IP address that is specified may fall somewhere in the middle of the range of IP addresses (not necessarily at the beginning).

In my script, I calculate the CIDR block members the correct way. I am converting the base IP address to its binary form, zeroing-out the number of least significant bits as specified in the subnet size, and starting the enumeration of IP addresses at the bottom of that range.

Hello Brandon.
I work in a phone company and i’m writing a security application in .net for my customer.
I was looking for a code snipped in C# for generate the ip range from 1-255 and i found your “Python CIDR Block Converter” very useful.
Now i can build my own class using the example you showed.
Of course if you like i’ll send you my class.
Thank you very much for posting it.