Tuesday, February 7, 2012

Translate a quad-dotted decimal netmask to its bit length equivalent

Here's an elegant way of translating a subnet netmask from its quad-dotted decimal representation to a bit length. The initial netmask is represented as a Python list. To get from the string representation to the list just do:

>>> b = "255.255.248.0".split(".")


to get the bitcount just do:

>>> reduce(lambda x, y: x + (y + 1)/32, b, 0)
23


 Modify to taste and njoy

2 comments:

Unknown said...

Thank you for this little tidbit of information. I am running python 2.6.6 and experienced an issue with the list generating a string and not able to calculate. I just remapped b to an integer with this line and all works great!!

b = map(int, b)

Script looks as such:

b = "255.255.248.0".split(".")
b = map(int, b)
reduce(lambda x, y: x + (y + 1)/32, b, 0)

There maybe a more elegant way to work this out, but I am in a hurry to finish and just need something to work at this time.

Unknown said...

I am a user of the best voip provider and i love it.