How use netaddr to convert subnet mask to cidr in Python

Mik picture Mik · Jun 28, 2016 · Viewed 33.4k times · Source

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

Answer

Eugene Yarmash picture Eugene Yarmash · Jun 28, 2016

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').prefixlen
24

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