Skip to content

Instantly share code, notes, and snippets.

@jayswan
Created February 11, 2012 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jayswan/1796357 to your computer and use it in GitHub Desktop.
Save jayswan/1796357 to your computer and use it in GitHub Desktop.
signed 32-bit int to ipv4
def int_to_ip(signed_int):
""" convert a 32-bit signed integer to an IP address"""
# do preventative type checking because I didn't want to check inputs
try:
if type(signed_int) == str or type(signed_int) == int:
signed_int = long(signed_int)
except ValueError:
return "err_ip"
# CUCM occasionally creates CDRs with an IP of '0'. Bug or feature? Beats me.
if signed_int == 0:
return "err_ip"
# hex conversion for 32-bit signed int;
# the slice at the end removes the '0x' and 'L' in the result
h = hex(signed_int & 0xffffffff)[2:-1]
if len(h) == 7: #pad initial zero if required
h = '0' + h
hex_ip = [h[6:8],h[4:6],h[2:4],h[:2]] # reverse the octets
#put them back together in IPv4 format
ip = '.'.join([str(int(n,16)) for n in hex_ip])
return ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment