The ntohl() function in Python

The ntohl() function in Python converts a 4 byte integer from network byte order to host byte order. Network byte order is big endian and the hosts are predominantly little endian.

socket Updated 1 Sep 2024 1 min read

Overview

  • The function ntohl() converts a 32-bit integer from network byter order to host byte order and returns the converted integer.
  • The network byter order is big endian. Chips from Intel, AMD and Apple M1, M2 and M3 chips use little endian architecture. The IBM z/Architecture uses big endian architecture.
  • The ntohl() does the inverse of what htonl() function does. When the host and the network byte order are the same, the ntohl() function returns the given parameter without any conversion.

Example

python
# Example Python program that converts a 32 bit integer

            # from network byter order to host byte order using

            # the function socket.ntohl()

import socket

            import struct

            import sys

# Number used for host versus network order conversion

            num = 1048572

# Print the byte order of the host system

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

numBytes = num.to_bytes(4, byteorder = 'little')

            print("Number in host byte order - before any conversion:%s"%numBytes)

# Get the network byte order

            nw = socket.htonl(num)

            nwOrder = nw.to_bytes(4, byteorder = 'little')

            print("Output of htonl - network byte order:%s"%nwOrder)

# Get the host byte order

            ht = socket.ntohl(nw)

            htOrder = ht.to_bytes(4, byteorder = 'little')

print("Output of ntohl - host byte order:%s"%htOrder)

Output

Output
Byte order of the host system:little

Number in host byte order - before any conversion:b'\xfc\xff\x0f\x00'

Output of htonl - network byte order:b'\x00\x0f\xff\xfc'

Output of ntohl - host byte order:b'\xfc\xff\x0f\x00'