convert cidr to subnet mask in python

just1han85 picture just1han85 · Nov 17, 2015 · Viewed 16.7k times · Source

I have a python dictionary that I've created, this dictionary contains a list of subnets in the following format:

x.x.x.x/24
y.y.y,y/25
z.z.z.z/26
a.a.a.a/27 

etc...

I would like to take the items in this dictionary, parse it, then spit out the results in the following format:

x.x.x.x 255.255.255.0
y.y.y.y 255.255.255.128
x.x.x.x 255.255.255.192
a.a.a.a 255.255.255.224 

I don't have much on this as of right now because I can't find a lot on this topic on the web, not anything that can be in a quick and concise way that is. Thoughts?

Answer

falsetru picture falsetru · Nov 17, 2015

Code:

import socket
import struct

def cidr_to_netmask(cidr):
    network, net_bits = cidr.split('/')
    host_bits = 32 - int(net_bits)
    netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
    return network, netmask

Usage:

>>> cidr_to_netmask('10.10.1.32/27')
('10.10.1.32', '255.255.255.224')
>>> cidr_to_netmask('208.128.0.0/11')
('208.128.0.0', '255.224.0.0')
>>> cidr_to_netmask('208.130.28.0/22')
('208.130.28.0', '255.255.252.0')