Reputation: 1651
How do I make the following conversion using python?
"172.1.3.1" >> "\xAC\x01\x03\x01"
currently I am able to make the following conversion:
"172.1.3.1" >> "AC010301"
However I require my results to have the hexadecimal escape characters as shown above.
Upvotes: 0
Views: 1620
Reputation: 50550
You can use the socket
module, if you are using Python 2.
>>> import socket
>>> socket.inet_aton("172.1.3.1")
'\xac\x01\x03\x01'
This utilizes inet_aton
:
Convert an IPv4 address from dotted-quad string format (for example, '123.45.67.89') to 32-bit packed binary format, as a string four characters in length.
If you are using Python 3:
>>> import ipaddress
>>> ipaddress.IPv4Address("172.1.3.1").packed
b'\xac\x01\x03\x01'
Upvotes: 3
Reputation: 798606
>>> socket.inet_aton('172.1.3.1')
'\xac\x01\x03\x01'
>>> struct.pack('>I', IPy.IP('172.1.3.1').int())
'\xac\x01\x03\x01'
Upvotes: 2