简体   繁体   中英

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

使用inet_ntop (适用于IPv4和IPv6)而不是inet_ntoa (仅适用于IPv4)。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM