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:

Source Code:

Sample Usage:

brandon@zodiac ~ $ cidr

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.

5 comments on “Python CIDR Block Converter

  1. Jose RR says:

    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 seems to work –of course, after I added the executable permission.

    Thank you, indeed!

  2. Jack Ross says:

    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.


  3. SubINacls says:

    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.

  4. Karim says:

    I search for CIDR calculator and I it writed with my favored language

    Thank you

  5. eric says:

    thanks allot for this script. its really handy

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>