【发布时间】:2012-05-17 19:11:46
【问题描述】:
我经常需要将原始的、字节编码的 IPv6 地址转换为来自 ipaddr-py project 的 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 的 v. 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 不行。
谁有更好的解决方案?
【问题讨论】:
标签: python ip-address