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
source
share