user2922822
user2922822

Reputation: 123

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.

Upvotes: 10

Views: 21529

Answers (5)

goldcountry
goldcountry

Reputation: 41

Since python v3.5 you can just do:

import socket
socket.inet_aton(ip).hex()

https://docs.python.org/3/library/stdtypes.html#typebytes

Upvotes: 2

user2968981
user2968981

Reputation: 31

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")

Upvotes: 3

sumit
sumit

Reputation: 7

>>>import binascii
>>>import socket
>>>binascii.hexlify(socket.inet_aton('115.255.8.97'))
'73ff0861'
>>>binascii.hexlify(socket.inet_aton('10.255.8.97'))
'0aff0861'

In above IP to hex conversion output, if the output start with '0' ex. 0aff0861 then I want to delete the 0 and output should looks like as aff0861. Is there any direct method available in conversion.

Upvotes: -1

Kobi K
Kobi K

Reputation: 7931

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])

Upvotes: 2

falsetru
falsetru

Reputation: 369054

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'

Upvotes: 14

Related Questions