I frequently need to convert a raw, byte-encoded IPv6 address into an IPv6Address object from the ipaddr-py project. Byte-encoded IPv6 addresses are not accepted by the initializer as shown here:
>>> 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
What is the easiest way to convert the byte-encoding to a format ipaddr-py can understand? I'm using v. 2.1.10 of ipaddr.py.
My only workaround so far is way too long for the simple task:
>>> 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')
EDIT: I'm looking for a cross-platform solution. Unix-only won't do.
Anyone got a better solution?