Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a IP to Hex by Python

I am writing a script to convert a IP to HEX. Below is my script:

import string
ip = raw_input('Enter IP')
a = ip.split('.')
b = hex(int(a[0])) + hex(int(a[1])) + hex(int(a[2])) + hex(int(a[3]))
b = b.replace('0x', '')
b = b.upper()
print b

My Problem is that for IP like 115.255.8.97, I am getting this:

Answer Coming : 73FF861

Expected Ans : 73FF0861

Can anyone is clever enough to tell me what mistake I am making.

like image 759
user2922822 Avatar asked Jan 06 '14 10:01

user2922822


3 Answers

hex function does not pad with leading zero.

>>> hex(8).replace('0x', '')
'8'

Use str.format with 02X format specification:

>>> '{:02X}'.format(8)
'08'
>>> '{:02X}'.format(100)
'64'

>>> a = '115.255.8.97'.split('.')
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*map(int, a))
'73FF0861'

Or you can use binascii.hexlify + socket.inet_aton:

>>> import binascii
>>> import socket
>>> binascii.hexlify(socket.inet_aton('115.255.8.97'))
'73ff0861'
>>> binascii.hexlify(socket.inet_aton('115.255.8.97')).upper()
'73FF0861'
like image 194
falsetru Avatar answered Sep 19 '22 18:09

falsetru


import socket, struct

# Convert a hex to IP
def hex2ip(hex_ip):
    addr_long = int(hex_ip,16)
    hex(addr_long)
    hex_ip = socket.inet_ntoa(struct.pack(">L", addr_long))
    return hex_ip

# Convert IP to bin
def ip2bin(ip):
    ip1 = '.'.join([bin(int(x)+256)[3:] for x in ip.split('.')])
    return ip1

# Convert IP to hex
def ip2hex(ip):
    ip1 = '-'.join([hex(int(x)+256)[3:] for x in ip.split('.')])
    return ip1

print hex2ip("c0a80100")
print ip2bin("192.168.1.0")
print ip2hex("192.168.1.0")
like image 37
user2968981 Avatar answered Sep 19 '22 18:09

user2968981


Since hex don't have leading leading zeros you can use zfill(2)

import string
ip = raw_input('Enter IP')
a = ip.split('.')
b = hex(int(a[0]))[2:].zfill(2) + hex(int(a[1]))[2:].zfill(2) + hex(int(a[2]))[2:].zfill(2) + hex(int(a[3]))[2:].zfill(2)
b = b.replace('0x', '')
b = b.upper()
print b

We are taking the hex number only with [2:] (remove '0x') and then we are adding 2 leading zeros only if needed.

Example output:

Enter IP 192.168.2.1
C0A80201

Example output:

Enter IP 115.255.8.97
73FF0861

Edit1:

by @volcano request you can replace with list comprehensions:

b = "".join([hex(int(value))[2:].zfill(2) for value in a])
like image 33
Kobi K Avatar answered Sep 19 '22 18:09

Kobi K