Created
June 10, 2017 02:22
-
-
Save ColdHeat/77f3019719af71b30fbb624fe1eb32a8 to your computer and use it in GitHub Desktop.
Functions to convert IP addresses to decimals and back
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
from socket import inet_pton, inet_ntop, AF_INET, AF_INET6 | |
from struct import unpack, pack, error as struct_error | |
def ip2long(ip): | |
'''Converts a user's IP address into an integer/long''' | |
if '.' in ip: | |
# ipv4 | |
return unpack('!i', inet_pton(AF_INET, ip))[0] | |
else: | |
# ipv6 | |
hi, lo = unpack('!QQ', inet_pton(AF_INET6, ip)) | |
return (hi << 64) | lo | |
def long2ip(ip_int): | |
'''Converts a saved IP address back into an integer/long''' | |
if ip_int < 4294967296: | |
# ipv4 | |
return inet_ntop(AF_INET, pack('!i', ip_int)) | |
else: | |
# ipv6 | |
return inet_ntop(AF_INET6, pack('!QQ', ip_int >> 64, ip_int & 0xffffffffffffffff)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment