Convert IPv6 address to binary representation on 2.x/Windows

Philipp Hagemeister phihag at phihag.de
Wed Mar 4 21:30:23 CET 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

socket.inet_pton which does exactly what I want is not available on 2.x
on Windows. Strangely, the documentation of socket.inet_aton (IPv4 only)
reads:

"inet_aton() does not support IPv6, and getnameinfo() should be used
instead for IPv4/v6 dual stack support."

Let's try that:

>>> def gni(flag, addr="::1", port=80):
...     try:
...             res = socket.getnameinfo((addr,port), flag)
...     except:
...             res = "error"
...     return res
...
>>> [(ni,gni(socket.__dict__[ni])) for ni in filter(lambda
k:k.startswith("NI_"), dir(socket))]

[('NI_DGRAM', ('localhost', 'www')), ('NI_MAXHOST', 'error'),
('NI_MAXSERV', ('localhost', 'www')), ('NI_NAMEREQD', ('localhost',
'www')), ('NI_NOFQDN', ('localhost', 'www')), ('NI_NUMERICHOST', ('::1',
'www')), ('NI_NUMERICSERV', ('localhost', '80'))]
>>>

Neither of these values looks like 0x0000000000000001. Am I missing
something or is the documentation just wrong? If so, how am I supposed
to get a binary representation of an IPv6 address in the absence of
socket.inet_pton? Should I write my I own version?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEAREKAAYFAkmu5N4ACgkQ9eq1gvr7CFwNUgCdF4QdT2LlWWXNlKYbBvKEeTlh
lDMAn2eGmFdx7rvM9+gr7tnHlENhgmq7
=Gsal
-----END PGP SIGNATURE-----



More information about the Python-list mailing list