The way to convert a netmask from dotted decimal notation (ABCD) to CIDR notation is previously posted, but you need to convert it the other way around. I was pressed by, so I wrote it.
No error handling is done, so if you pass a strange netmask, a strange value will be returned. Please be careful.
import socket
import struct
def mask2cidr(mask):
"""Convert netmask from Dotted address to CIDR."""
return bin(struct.unpack('!L', socket.inet_pton(socket.AF_INET, mask))[0])[2:].index('0')
>>> mask2cidr('255.255.255.0')
24
>>> mask2cidr('255.255.240.0')
20
>>> mask2cidr('255.255.255.192')
26
-Convert CIDR notation with Python --Qiita
Recommended Posts