Created
April 2, 2014 20:03
-
-
Save topnotcher/9941992 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ip2n(ip): | |
""" | |
Convert an IP address in dotted quad to an integer | |
""" | |
octets = ip.split('.') | |
return sum([(int(octets[x]))<<(24-(8*x)) for x in range(0,4)]) | |
def n2ip(n): | |
""" | |
Convert an integer to a dotted quad ip address | |
""" | |
return '.'.join( [str((n>>(24-(8*x)))&0xff) for x in range(0,4)] ) | |
def cidrbits2mask(bits): | |
""" | |
Given a number of bits (i.e. /bits), return a subnet mask | |
""" | |
return n2ip(0xffffffff & ~int((2**(32-bits)-1))) | |
def cidr2range(cidr): | |
""" | |
Convert CIDR notation to a range. | |
""" | |
net,bits = cidr.split('/') | |
bits = int(bits) | |
net = ip2n(net)&ip2n(cidrbits2mask(bits)) | |
return (n2ip(net), n2ip(net+2**(32-bits)-1)) | |
if __name__ == '__main__': | |
print(n2ip(ip2n('192.168.1.1'))) | |
print(cidr2range('192.168.1.0/24')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment