2

我经常需要将原始的字节编码 IPv6 地址转换为ipaddr-py 项目中的 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 不行。

有人有更好的解决方案吗?

4

2 回答 2

2

在 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'
于 2012-05-09T09:52:40.243 回答
1

看看ipaddr_test.py

[...]
# Compatibility function to cast str to bytes objects
if issubclass(ipaddr.Bytes, str):
    _cb = ipaddr.Bytes
else:
    _cb = lambda bytestr: bytes(bytestr, 'charmap')
[...]

然后

_cb('\x20\x01\x06\x58\x02\x2a\xca\xfe'
    '\x02\x00\x00\x00\x00\x00\x00\x01')

为您提供Bytes模块识别的包含压缩地址的对象。

我没有测试它,但它看起来好像是它的意图......


同时我测试了它。这些_cb东西可能适用于没有Bytes对象的旧 moule 版本。所以你可以做

import ipaddr
b = ipaddr.Bytes('\x20\x01\x06\x58\x02\x2a\xca\xfe' '\x02\x00\x00\x00\x00\x00\x00\x01')
print ipaddr.IPAddress(b)

这将导致

2001:658:22a:cafe:200::1

这可能是你需要的。

于 2012-05-09T11:24:02.930 回答