Python Glossary Русский

all Python 3socketfunction

socket.ntohl()

address and byte-order conversion

Converts a 32-bit integer from network byte order (big-endian) to host order; the inverse of htonl().

Syntax

socket.ntohl(x) -> int

The function works on ints, while a socket delivers bytes, and that is where people get confused: ntohl applies to a number read in host order. It is simpler to read the bytes in the right order at once with int.from_bytes(data, 'big') or struct.unpack('!I', data), and ntohl is not needed. Applying it twice undoes it: ntohl(htonl(x)) == x.

Examples

import socket, struct, sys
data = b'\x00\x00\x01\x00'  # 256 в сетевом порядке
print(socket.ntohl(int.from_bytes(data, sys.byteorder)))  # → 256
print(int.from_bytes(data, 'big'))  # → 256
print(struct.unpack('!I', data)[0])  # → 256
print(socket.ntohl(socket.htonl(123456)))  # → 123456

See also

Open in the full glossarydocs.python.orgReport an inaccuracy