简体   繁体   中英

IPv4 Address to Hex in python

I am trying to create a program that takes a string IPv4 address and converts it to a hexadecimal integer. My program works, however the hexadecimal value is in the form of a string, so my program returns value errors (eg: "invalid literal for int() with base 10", or "expected type int() or float()...").

example input: 115.255.8.97
example output: 73FF0861


#IPv4 to Hex
splitip = sys.argv[2].split('.')
hexint = hex(int(splitip[0]))[2:].zfill(2) + hex(int(splitip[1]))[2:].zfill(2) + hex(int(splitip[2]))[2:].zfill(2) + hex(int(splitip[3]))[2:].zfill(2)
hexint = hexint.replace('0x','')

Any help would be appreciated!

Note: My problem is that the hexint variable is a string. My program needs to have the value ad an integer.

Use socket.inet_aton to convert dotted IPv4 address to byte string.

>>> import socket
>>> socket.inet_aton('115.255.8.97')
's\xff\x08a'

Then, pass the value to binascii.hexlify to get hexa-decimal representation of the binary string.

>>> import binascii
>>> binascii.hexlify(socket.inet_aton('115.255.8.97'))
'73ff0861'
>>> binascii.hexlify(socket.inet_aton('115.255.8.97')).upper()
'73FF0861'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM