[英]Converting IP addresses to Hex
How do I make the following conversion using python? 如何使用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. 但是,我要求我的结果必须具有如上所示的十六进制转义字符。
You can use the socket
module, if you are using Python 2. 如果使用的是Python 2,则可以使用
socket
模块。
>>> import socket
>>> socket.inet_aton("172.1.3.1")
'\xac\x01\x03\x01'
This utilizes inet_aton
: 这利用了
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.
将IPv4地址从点分四进制字符串格式(例如'123.45.67.89')转换为32位压缩二进制格式,即长度为四个字符的字符串。
If you are using Python 3: 如果您使用的是Python 3:
>>> import ipaddress
>>> ipaddress.IPv4Address("172.1.3.1").packed
b'\xac\x01\x03\x01'
>>> 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.