The ntohs() function in Python

The ntohs() function converts a 16-bit integer from network byte order to host byte order.

socket Updated 3 Sep 2024 1 min read

Overview

  • The function ntohs() converts a two-byte integer from network byte order to host byte order.
  • It does the inverse operation of the htons() function.
  • When the size of the integer to be converted is greater than 16 bytes ntohs() raises an exception stating "OverflowError: ntohs: Python int too large to convert to C 16-bit unsigned integer".

Example

python
# Example Python program that converts a two-byte

            # integer from network byte order to host byte order

            import socket

            import sys

print("Byte order of the host:%s endian"%sys.byteorder)

# 16-bit integer to be converted

            num     = 65534

# Convert to network order first

            nwNum = socket.htons(num)

            print(nwNum)

            hNum =  socket.ntohs(nwNum)

            print(hNum)

print("Network byte order: %s"%nwNum.to_bytes(2, byteorder='little'))

            print("Host byte order:%s"%hNum.to_bytes(2, byteorder='little'))

Output

Output
Byte order of the host:little endian

65279

65534

Network byte order: b'\xff\xfe'

Host byte order:b'\xfe\xff'