IPv4 CIDR to netmask in Python
I needed small function to validate IPv4 netmasks, havent found one, so I wrote my own. I’ve decided to use IPv4 CIDR notation to get corresponding netmasks. Here is the code:
def ipv4_cidr_to_netmask(bits):
""" Convert CIDR bits to netmask """
netmask = ''
for i in range(4):
if i:
netmask += '.'
if bits >= 8:
netmask += '%d' % (2**8-1)
bits -= 8
else:
netmask += '%d' % (256-2**(8-bits))
bits = 0
return netmask
Example usage is presented below. They also show how lambda mappings are useful in regular, daily use.
List all possible netmasks:
for netmask in map(lambda x: ipv4_cidr_to_netmask(x), range(0,33)):
print netmask
0.0.0.0
128.0.0.0
192.0.0.0
224.0.0.0
240.0.0.0
248.0.0.0
252.0.0.0
254.0.0.0
255.0.0.0
255.128.0.0
255.192.0.0
255.224.0.0
255.240.0.0
255.248.0.0
255.252.0.0
255.254.0.0
255.255.0.0
255.255.128.0
255.255.192.0
255.255.224.0
255.255.240.0
255.255.248.0
255.255.252.0
255.255.254.0
255.255.255.0
255.255.255.128
255.255.255.192
255.255.255.224
255.255.255.240
255.255.255.248
255.255.255.252
255.255.255.254
255.255.255.255
Get netmask for /24:
print ipv4_cidr_to_netmask(24) 255.255.255.0
Is 255.255.254.0 valid IPv4 netmask?
print "255.255.254.0" in map(lambda x: ipv4_cidr_to_netmask(x), range(0,33)) True
Reverse search – get CIDR for 255.255.192.0 netmask
print map(lambda x: ipv4_cidr_to_netmask(x), range(0,33)).index('255.255.254.0')
23
As usual – enjoy

And here is analogous function rewritten to Javascript:
var cidrToNetmask = function(bits) { var netmask = ''; for (var i=0;i<4;i++) { if (i !== 0) { netmask += '.'; } if (bits >= 8) { netmask += Math.pow(2,8)-1; bits -= 8; } else { netmask += 256-Math.pow(2,8-bits); bits = 0; } } return netmask; }