Python Glossary Русский

all Python 3socketfunction

socket.inet_pton()

address and byte-order conversion

Converts an IPv4 or IPv6 address string into bytes (4 or 16) for the given address family.

Syntax

socket.inet_pton(address_family, ip_string) -> bytes

Unlike inet_aton it is strict: '127.1' with AF_INET is rejected with OSError. The family must be given explicitly and is never guessed: an IPv6 address with AF_INET also raises OSError. To parse and validate without knowing the family in advance, ipaddress.ip_address(s).packed is handier.

Examples

import socket
print(len(socket.inet_pton(socket.AF_INET6, '::1')))  # → 16
print(socket.inet_pton(socket.AF_INET, '10.0.0.1'))  # → b'\n\x00\x00\x01'
socket.inet_pton(socket.AF_INET, '127.1')  # → OSError: illegal IP address string passed to inet_pton

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy