1

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.

G Broad
  • 11
  • 4
  • Possible duplicate of [Convert hex string to int in Python](https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python) – tinamou Jun 23 '17 at 13:44

1 Answers1

0

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • The output can't be a string. – G Broad Jun 26 '17 at 15:15
  • @GBroad, I don't get it. What do you mean? – falsetru Jun 26 '17 at 15:51
  • using that code, the output is a string. my program can't use a hex string. the other hex values that i have in my program aren't strings, and i'm having trouble converting the string output to one that my program can use. – G Broad Jun 26 '17 at 18:32
  • @GBroad, Are you sure you're using Python 2.7? If you are using Python 3.x, use `binascii.hexlify(socket.inet_aton('115.255.8.97')).decode().upper()` instead. (decode to convert bytes to string) – falsetru Jun 26 '17 at 21:39
  • my program runs on python 2.7. I'm not having trouble converting the IP addresses to hex, i'm having trouble with the type of the output. in some parts of my program, i have variables assigned with hex values that are not strings, so i can't have the output be a string. – G Broad Jun 27 '17 at 15:18
  • @GBroad, I still don't understand your problem. Could you post a separate question (not comment) with example? – falsetru Jun 27 '17 at 16:01