all Python 3socketfunction
socket.ntohs()
address and byte-order conversion
Converts a 16-bit integer from network byte order (big-endian) to host order; the inverse of htons().
Syntax
socket.ntohs(x) -> int
It applies to a number, not to bytes: the two port bytes from a header are first turned into an int and only then swapped. int.from_bytes(data, 'big') or struct.unpack('!H', data) is shorter. Since 3.10 a value above 65535 raises OverflowError; before that the high bits were dropped with only a DeprecationWarning and the bug stayed hidden. Since 3.14 a negative value raises ValueError.
Examples
import socket, sys
data = (8080).to_bytes(2, 'big') # порт в заголовке пакета
print(socket.ntohs(int.from_bytes(data, sys.byteorder))) # → 8080
print(int.from_bytes(data, 'big')) # → 8080
# Python 3.10+
import socket
socket.ntohs(70000) # → OverflowError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy