Convert IPv4 decimal (base 10) addresses to hex (base 16). Useful for 6to4 tunnel configs.
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
#!/usr/bin/python | |
import sys | |
import re | |
def DecToHex(dec_ip): | |
dec_octets = str.split(dec_ip, '.') | |
hex_octets = [] | |
if len(dec_octets) != 4: | |
print 'usage: ./iptohex.py x.x.x.x' | |
sys.exit(1) | |
for dec_octet in dec_octets: | |
if int(dec_octet) > 255: | |
print 'usage: ./iptohex.py x.x.x.x' | |
sys.exit(1) | |
if int(dec_octet) < 16: | |
hex_octets.append('0' + hex(int(dec_octet))[2:]) | |
else: | |
hex_octets.append(hex(int(dec_octet))[2:]) | |
hex_octets.insert(2, ':') | |
hex_ip = ''.join(hex_octets) | |
return hex_ip | |
def main(): | |
if (len(sys.argv) != 2): | |
print 'usage: ./iptohex.py x.x.x.x' | |
sys.exit(1) | |
dec_ip = sys.argv[1] | |
invalid = re.search(r'[^0-9\.]', dec_ip) | |
if invalid: | |
print 'usage: ./iptohex.py x.x.x.x' | |
sys.exit(1) | |
hex_ip = DecToHex(dec_ip) | |
print '\nIPv4 Hex Address:\t', hex_ip | |
print '6to4 Tunnel Address:\t', '2002:' + hex_ip | |
print '\nCopyright (C) 2011 13Cubed. All rights reserved.' | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment