【问题标题】:Create ipaddr-py IPv6Address from byte string从字节字符串创建 ipaddr-py IPv6Address
【发布时间】: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


    【解决方案1】:

    在 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'
    

    【讨论】:

    • 非常干净的解决方案,谢谢。不幸的是,我需要一个跨平台的解决方案。至少 *nix 和 Win32。
    【解决方案2】:

    看看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
    

    这可能是你需要的。

    【讨论】:

    • 宾果游戏,ipaddr.IPAddress(ipaddr.Bytes(byte_ip)) 就像一个魅力。我认为 _cb 的东西是为了兼容 Python3。
    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 2020-09-15
    • 2012-03-09
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多