Convert IP to Hex with Python

I am writing a script to convert 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, for example, 115.255.8.97, I get the following:

Answer Comes: 73FF861

Expected Warning: 73FF0861

Can someone smart to tell me what mistake I am making.

+6
source share
4 answers

hex function does not fit with a leading zero.

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

Use str.format with 02X format 02X :

 >>> '{: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' 
+12
source

Since hex does not 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 take the hexadecimal number only with [2:] (delete '0x'), and then add only 2 leading zeros only if necessary.

Output Example:

 Enter IP 192.168.2.1 C0A80201 

Output Example:

 Enter IP 115.255.8.97 73FF0861 

Edit1:

by @volcano you can replace it with a list:

 b = "".join([hex(int(value))[2:].zfill(2) for value in a]) 
+1
source
 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") 
0
source
 >>>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 the above conversion output, IP is hexadecimal if the output starts with '0' ex. 0aff0861, then I want to remove 0, and the output should look like aff0861. Is there any direct method available when converting.

-1
source

All Articles