The ntohs() function in Python

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:

# 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:

Byte order of the host:little endian

65279

65534

Network byte order: b'\xff\xfe'

Host byte order:b'\xfe\xff'

 


Copyright 2024 © pythontic.com