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:
Source Code: cidr.py
brandon@zodiac ~ $ cidr 192.168.1.5/30 192.168.1.4 192.168.1.5 192.168.1.6 192.168.1.7
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.
I was searching for cidr utility in Perl and Google search suggested the “cidr Python” entry 🙂
After download with wget, I fed it an sample and cidr.py seems to work –of course, after I added the executable permission.
Thank you, indeed!
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.
I was looking for something to make my targeting list easier and ran into this. It worked flawless for the use where I needed this. Slightly after I got ideas for other scripts based off this concept.
Thank you for your time to post this example for the rest of us.
I search for CIDR calculator and I it writed with my favored language
thanks allot for this script. its really handy