How to use netaddr to convert subnet mask to cidr in Python

How can I convert ipv4 subnet mask to cidr notation using library netaddr?
Example:255.255.255.0 to /24

+4
source share
3 answers

Usage netaddr:

>>> from netaddr import IPAddress
>>> IPAddress("255.255.255.0").netmask_bits()
24

You can also do this without using any libraries, just recount 1 bit in the binary representation of the netmask:

>>> netmask = "255.255.255.0"
>>> sum([bin(int(x)).count("1") for x in netmask.split(".")])
24
+10
source
>>> IPNetwork('0.0.0.0/255.255.255.0').prefixlen
24
+3
source

Use the following function. it is fast, reliable and uses no library.

# code to convert netmask ip to cidr number
def netmask_to_cidr(netmask):
    '''
    :param netmask: netmask ip addr (eg: 255.255.255.0)
    :return: equivalent cidr number to given netmask ip (eg: 24)
    '''
    return sum([bin(int(x)).count('1') for x in netmask.split('.')])
0
source

All Articles