How can I convert a ipv4 subnet mask to cidr notation using netaddr
library?
Example: 255.255.255.0 to /24
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.
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 .
These networks use the 255.255. 0.0 subnet mask, or /16 CIDR notation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With