Last active
January 2, 2020 19:44
-
-
Save javiermon/94fb91d0120bb534d0349904dc347e5b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import sys | |
# example: | |
# python int2ip.py -1062731768 | |
# 192.168.0.8 | |
# | |
# stolen from: https://pastebin.com/icqSZhYt | |
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 = int(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' in the result | |
h = hex(signed_int & 0xffffffff)[2:] | |
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 = [str(int(n,16)) for n in hex_ip] | |
ip.reverse() | |
return '.'.join(ip) | |
if __name__== "__main__": | |
print(int_to_ip(int(sys.argv[1]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment