从字节字符串创建ipaddr-py IPv6Address

时间:2012-05-09 09:23:24

标签: python ip-address

我经常需要将原始的字节编码的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的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才行。

任何人都有更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

在Unix IPv6 bin上 - &gt;字符串转换很简单 - 您只需要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'

答案 1 :(得分: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

这可能是你需要的。