Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert cidr to subnet mask in python

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?

like image 316
just1han85 Avatar asked Nov 17 '15 06:11

just1han85


People also ask

What is the fastest way to calculate CIDR?

The formula to calculate the number of assignable IP address to CIDR networks is similar to classful networking. Subtract the number of network bits from 32. Raise 2 to that power and subtract 2 for the network and broadcast addresses. For example, a /24 network has 232-24 - 2 addresses available for host assignment.

How do I find the CIDR of an IP address?

The CIDR number is typically preceded by a slash “/” and follows the IP address. For example, an IP address of 131.10. 55.70 with a subnet mask of 255.0. 0.0 (which has 8 network bits) would be represented as 131.10.


1 Answers

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')
like image 158
falsetru Avatar answered Sep 28 '22 03:09

falsetru