all Python 3socketfunction
socket.htons()
address and byte-order conversion
Converts a 16-bit integer from host byte order to network order (big-endian); the result is again an int.
Syntax
socket.htons(x) -> int
A common surprise: the function returns a number with swapped bytes, not bytes, and on a little-endian machine htons(80) equals 20480. To pack into bytes, struct.pack('!H', n) or n.to_bytes(2, 'big') is clearer: the order is explicit and the result is ready to send. Since 3.10 a value above 65535 raises OverflowError (earlier it was truncated with only a DeprecationWarning), and since 3.14 a negative one raises ValueError.
Examples
import socket, sys
x = socket.htons(80)
print(type(x).__name__) # → int
print(x == int.from_bytes((80).to_bytes(2, 'big'), sys.byteorder)) # → True
print(x) # → ? 20480 на little-endian (x86, ARM)
# Python 3.10+
import socket
socket.htons(70000) # → OverflowError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy