Mat*_*ner 8 python sockets ip-address endianness
将此表单中的字符串转换为IP地址的最佳方法是:"0200A8C0"
.字符串中出现的"八位字节"是相反的顺序,即应该生成给定的示例字符串192.168.0.2
.
gim*_*mel 32
套接字模块提供网络地址操作.
将32位打包的IPv4地址(长度为四个字符的字符串)转换为标准的点分四字符串表示形式(例如,"123.45.67.89").当与使用标准C库的程序进行对话并且需要struct in_addr类型的对象时,这非常有用,该对象是此函数用作参数的32位压缩二进制数据的C类型.
您可以将十六进制字符串转换为packed ip
使用struct.pack()
和小端,无符号长格式.
>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)
小智 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
Run Code Online (Sandbox Code Playgroud)
它简短明了; 将它包装在一个错误检查功能中,以满足您的需求.
方便的分组功能:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19194 次 |
最近记录: |