Python Glossary Русский

all Python 3socketfunction

socket.htonl()

address and byte-order conversion

Converts a 32-bit integer from host byte order to network order (big-endian); the result is again an int.

Syntax

socket.htonl(x) -> int

On a big-endian machine it does nothing; on little-endian ones (nearly every PC and phone) it swaps 4 bytes, which is why htonl(1) prints a scary 16777216. It is a legacy of the C API; in Python a protocol field is usually packed straight into bytes with struct.pack('!I', n) or n.to_bytes(4, 'big'). Negative values and values above 2**32-1 are rejected.

Examples

import socket, struct
print(socket.htonl(1))  # → ? 16777216 на little-endian
print(struct.pack('!I', 1))  # → b'\x00\x00\x00\x01'
print((1).to_bytes(4, 'big'))  # → b'\x00\x00\x00\x01'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy