我經常需要將原始的字節編碼的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才行。
任何人都有更好的解決方案嗎?
Bingo,'ipaddr.IPAddress(ipaddr.Bytes(byte_ip))'就像一個魅力。我認爲_cb的東西是爲了兼容Python3。 –