转换“ little endian”十六进制字符串到Python中的IP地址 [英] Convert "little endian" hex string to IP address in Python
问题描述
将这种形式的字符串转换为IP地址的最佳方法是什么: 0200A8C0
。字符串中出现的八位字节是相反的顺序,即给定的示例字符串应生成 192.168.0.2
。
What's the best way to turn a string in this form into an IP address: "0200A8C0"
. The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2
.
推荐答案
套接字模块提供了网络地址处理。
Network address manipulation is provided by the socket module.
将32位压缩的IPv4地址(长度为四个字符的字符串)转换为其标准的点分四进制字符串表示形式(例如'123.45.67.89')。在与使用标准C库并且需要struct in_addr类型的对象的程序进行对话时,此功能很有用。这是该函数作为参数的32位打包二进制数据的C类型。
Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.
您可以使用 struct.pack()
和小端无符号长格式。
You can translate your hex string to packed ip
using struct.pack()
and the little endian, unsigned long format.
>>> import socket
>>> import struct
>>> addr_long = int("0200A8C0",16)
>>> hex(addr_long)
'0x200a8c0'
>>> struct.pack("<L", addr_long)
'\xc0\xa8\x00\x02'
>>> socket.inet_ntoa(struct.pack("<L", addr_long))
'192.168.0.2'
>>>
这篇关于转换“ little endian”十六进制字符串到Python中的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!