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

How use netaddr to convert subnet mask to cidr in Python


Using netaddr:

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

Using ipaddress from stdlib:

>>> from ipaddress import IPv4Network>>> IPv4Network('0.0.0.0/255.255.255.0').prefixlen24

You can also do it without using any libraries: just count 1-bits in the binary representation of the netmask:

>>> netmask = '255.255.255.0'>>> sum(bin(int(x)).count('1') for x in netmask.split('.'))24


>>> IPNetwork('0.0.0.0/255.255.255.0').prefixlen24


Use the following function. it is fast, reliable, and don't use any library.

# code to convert netmask ip to cidr numberdef 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('.')])