Skip to content

Instantly share code, notes, and snippets.

@ColdHeat
Created June 10, 2017 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ColdHeat/77f3019719af71b30fbb624fe1eb32a8 to your computer and use it in GitHub Desktop.
Save ColdHeat/77f3019719af71b30fbb624fe1eb32a8 to your computer and use it in GitHub Desktop.
Functions to convert IP addresses to decimals and back
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