Python Glossary Русский

all Python 3socketfunction

socket.inet_ntop()

address and byte-order conversion

Converts the bytes of an IPv4 or IPv6 address into its canonical string for the given family.

Syntax

socket.inet_ntop(address_family, packed_ip) -> str

Handy for normalising IPv6: '2001:0db8:0000::0001' round-trips to '2001:db8::1', so the strings become comparable. A wrong byte length raises ValueError, not OSError as in inet_ntoa, so catch both. The family and length must match: 4 bytes with AF_INET, 16 with AF_INET6.

Examples

import socket
packed = socket.inet_pton(socket.AF_INET6, '2001:0db8:0000:0000::0001')
print(socket.inet_ntop(socket.AF_INET6, packed))  # → 2001:db8::1
try:
    socket.inet_ntop(socket.AF_INET, b'abc')
except ValueError as e:
    print(type(e).__name__)  # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy