Created
June 4, 2014 13:44
-
-
Save spoterianski/a91b7fcc4da7f9c22daf to your computer and use it in GitHub Desktop.
Convert IP to int and back from int to IP
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
""" | |
Convert IPv4 to unsigned int | |
""" | |
def ip2uint(ip): | |
dot1 = ip.index('.') | |
dot2 = ip.index('.', dot1 + 1) | |
dot3 = ip.index('.', dot2 + 1) | |
i1 = int(ip[0: dot1]) | |
i2 = int(ip[dot1 + 1: dot2]) | |
i3 = int(ip[dot2 + 1: dot3]) | |
i4 = int(ip[dot3 + 1:]) | |
uintip = (i1 << 24) + (i2 << 16) + (i3 << 8) + i4 | |
return uintip | |
""" | |
Convert IPv4 stored in unsigned int back to string | |
""" | |
def uint2ip(uintip): | |
x1 = uintip >> 24 | |
x2 = (uintip - (x1 << 24)) >> 16 | |
x3 = (uintip - (x1 << 24) - (x2 << 16)) >> 8 | |
x4 = (uintip - (x1 << 24) - (x2 << 16) - (x3 << 8)) | |
return '{0}.{1}.{2}.{3}'.format(x1, x2, x3, x4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment