The htons() function in Python

The htons() function of the socket module in Python converts a 16-bit integer from host byte order to network byte order. Host byte order is predominanatly little endian and network byte order is big endian.

socket Updated 3 Sep 2024 1 min read

Overview

  • The function htons() converts a two-byte integer from host byte order to network byte order and returns the converted integer.
  • The htonl() function provides the similar functionality and it works on a four-byte integer.

Example

python
# Example Python program that converts a 16-bit intger

            # from host byte order to network byte order

            import socket

            import sys

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

# 16-bit integer to be converted

            num     = 65534

            print(num)

# Convert the integer from host byte order

            # to network byte order

            nw         = socket.htons(num)

            print(nw)

# Print the 16-bit integer in host byte order

            bytes_hostOrder = num.to_bytes(2, byteorder = 'little')

            print("Given 16-bit integer in little endian format:%s"%bytes_hostOrder)

# Print the bytes of the 16-bit integer whose byte order is changed to

            # big endian(the converted integer itself is stored in little endian...as the

            # platform is little endian)

            bytes_nwOrder     = nw.to_bytes(2, byteorder = 'little')

            print("Given 16-bit integer in big endian format:%s"%bytes_nwOrder)

Output

Output
Byte order of the host:little

65534

65279

Given 16-bit integer in little endian format:b'\xfe\xff'

Given 16-bit integer in big endian format:b'\xff\xfe'