In Python, it seems that you can do it by using a module called netaddr, I only needed CIDR conversion, so I wrote it myself.
>>> import socket, struct
>>> def cidr2mask(len):
... return socket.inet_ntoa(struct.pack('!L', 0xffffffff ^ ((1 << 32-len)-1)))
...
>>> cidr2mask(8)
'255.0.0.0'
>>> cidr2mask(16)
'255.255.0.0'
>>> cidr2mask(24)
'255.255.255.0'
>>> cidr2mask(20)
'255.255.240.0'
There seems to be a more elegant way of writing.
Recommended Posts