将此表单中的字符串转换为IP地址的最佳方法是:"0200A8C0"
。字符串中出现的“八位字节”的顺序相反,即给定的示例字符串应生成192.168.0.2
。
答案 0 :(得分:32)
套接字模块提供网络地址操作。
将32位打包的IPv4地址(长度为四个字符的字符串)转换为标准的点分四字符串表示形式(例如,“123.45.67.89”)。当与使用标准C库的程序进行对话并且需要struct in_addr类型的对象时,这非常有用,该对象是此函数作为参数的32位压缩二进制数据的C类型。
您可以使用struct.pack()
将十六进制字符串翻译为packed ip
和小端,无符号长格式。
>>> 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'
>>>
答案 1 :(得分:5)
>>> s = "0200A8C0"
>>> bytes = ["".join(x) for x in zip(*[iter(s)]*2)]
>>> bytes
['02', '00', 'A8', 'C0']
>>> bytes = [int(x, 16) for x in bytes]
>>> bytes
[2, 0, 168, 192]
>>> print ".".join(str(x) for x in reversed(bytes))
192.168.0.2
简短明了;将它包装在一个错误检查功能中,以满足您的需求。
便捷的分组功能:
def group(iterable, n=2, missing=None, longest=True):
"""Group from a single iterable into groups of n.
Derived from http://bugs.python.org/issue1643
"""
if n < 1:
raise ValueError("invalid n")
args = (iter(iterable),) * n
if longest:
return itertools.izip_longest(*args, fillvalue=missing)
else:
return itertools.izip(*args)
def group_some(iterable, n=2):
"""Group from a single iterable into groups of at most n."""
if n < 1:
raise ValueError("invalid n")
iterable = iter(iterable)
while True:
L = list(itertools.islice(iterable, n))
if L:
yield L
else:
break
答案 2 :(得分:2)
你可以这样做:
>>> s = '0200A8C0'
>>> octets = [s[i:i+2] for i in range(0, len(s), 2)]
>>> ip = [int(i, 16) for i in reversed(octets)]
>>> ip_formatted = '.'.join(str(i) for i in ip)
>>> print ip_formatted
192.168.0.2
八分音符分裂可能会更优雅,但我想不出更简单的方法。
编辑或者在一行:
>>> s = '0200A8C0'
>>> print '.'.join(str(int(i, 16)) for i in reversed([s[i:i+2] for i in range(0, len(s), 2)]))
192.168.0.2
答案 3 :(得分:0)
我的尝试:
a = '0200A8C0'
indices = range(0, 8, 2)
data = [str(int(a[x:x+2], 16)) for x in indices]
'.'.join(reversed(data))