2012-05-09 7 views
2

我經常需要將原始的字節編碼的IPv6地址轉換爲ipaddr-py project中的IPv6Address對象。如下所示字節編碼的IPv6地址不被初始化接受:從字節字符串中創建ipaddr-py IPv6Address

>>> 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才行。

任何人都有更好的解決方案嗎?

回答

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對象被模塊識別爲con打包地址。

我沒有測試它,但它看起來好像是它的目的是這樣......


同時我測試了它。 _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 

這可能是你所需要的。

+0

Bingo,'ipaddr.IPAddress(ipaddr.Bytes(byte_ip))'就像一個魅力。我認爲_cb的東西是爲了兼容Python3。 –

1

在Unix平臺上的IPv6斌 - >字符串轉換很簡單 - 所有你需要的是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' 
+0

非常乾淨的解決方案,謝謝。不幸的是我需要一個跨平臺的解決方案。至少* nix和Win32。 –