Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use netaddr to convert subnet mask to cidr in Python

Tags:

python

cidr

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

like image 451
Mik Avatar asked Jun 28 '16 20:06

Mik


People also ask

How do I convert subnet mask to CIDR?

The CIDR number comes from the number of ones in the subnet mask when converted to binary. The subnet mask 255.255. 255.0 is 11111111.11111111. 11111111.00000000 in binary.

Is CIDR the same as subnet mask?

CIDR notation is really just shorthand for the subnet mask, and represents the number of bits available to the IP address. For instance, the /24 in 192.168.0.101/24 is equivalent to the IP address 192.168.0.101 and the subnet mask 255.255.255.0 .

What is the subnet mask corresponding to CIDR value of 16?

These networks use the 255.255. 0.0 subnet mask, or /16 CIDR notation.


1 Answers

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
like image 139
Eugene Yarmash Avatar answered Oct 10 '22 17:10

Eugene Yarmash