Elad Weiss
Elad Weiss

Reputation: 4002

How can I decode/print an IPV6 address in python

I have an IPv6 address, and I would like to print it in a human readable format.

On an IPv4 address I did socket.inet_ntoa(...), but on IPv6 I get

socket.error: packed IP wrong length for inet_ntoa

Upvotes: 0

Views: 4143

Answers (2)

Błotosmętek
Błotosmętek

Reputation: 12927

Use inet_ntop (which works for both IPv4 and IPv6) instead of inet_ntoa (which is IPv4-only).

print(socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, '10::' )))

Upvotes: 2

omri_saadon
omri_saadon

Reputation: 10631

From the documentation:

socket.inet_ntoa(packed_ip) Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.

If the string passed to this function is not exactly 4 bytes in length, socket.error will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support.

You can use the library IPy in order to take care of IPv4 and IPv6.

>>> print(IP('1080:0:0:0:8:800:200C:417A'))
1080::8:800:200c:417a

Upvotes: 1

Related Questions