我经常需要将 ipaddr-py project 中的原始字节编码 IPv6 地址转换为 IPv6Address 对象。 。初始化程序不接受字节编码的 IPv6 地址,如下所示:
>>> import ipaddr
>>> byte_ip = b'\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
>>> ipaddr.IPAddress(byte_ip)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ipaddr.py", line 78, in IPAddress
address)
ValueError: ' \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' does
not appear to be an IPv4 or IPv6 address
将字节编码转换为 ipaddr-py 可以理解的格式的最简单方法是什么? 我使用的是 ipaddr.py 2.1.10 版。
到目前为止,我唯一的解决方法对于简单的任务来说太长了:
>>> def bytes_to_ipaddr_string(c):
... c = c.encode('hex')
... if len(c) is not 32: raise Exception('invalid IPv6 address')
... s = ''
... while c is not '':
... s = s + ':'
... s = s + c[:4]
... c = c[4:]
... return s[1:]
...
>>> ipaddr.IPAddress(bytes_to_ipaddr_string(byte_ip))
IPv6Address('2000::1')
编辑:我正在寻找跨平台解决方案。仅 Unix 不行。
谁有更好的解决方案?
最佳答案
在 Unix IPv6 bin -> 字符串转换很简单 - 您所需要的只是 socket.inet_ntop
:
>>> socket.inet_ntop(socket.AF_INET6, b'\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01')
'2000::1'
关于python - 从字节字符串创建 ipaddr-py IPv6Address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513235/