Unix Socket Network Byte Orders - Unix socket

What is a Network Byte order in Unix Socket?

Not all computers store bytes that make up multibyte values in the same order. Let's consider a 16-bit Internet consisting of 2 bytes. There are two ways to store this value.

  • Small Endian : In this method, the low byte is stored in the start address (A), and the high byte is stored in the next address (A + 1).
  • Large Endian : In this method, the high byte is stored in the start address (A), and the low byte is stored in the next address (A + 1).

In order to allow machines with different byte ordering rules to communicate with each other, the Internet protocol specifies a standard ordering rule for data sent over the network. This is called network byte order.

When establishing an Internet socket connection, make sure that the data for the sin_port and sin_addr members of the sockaddr_in structure is represented by the network byte order.

Byte Ordering Functions

The routines for converting data between the internal representation of the host and the network byte order are as follows :

Function Description
htons() Host to Network Short
htonl() Host to Network Long
ntohl() Network to Host Long
ntohs() Network to Host Short

The details of these functions are shown below:

  • unsigned short button (unsigned short host) : This function converts 16 bits (2 byte) number from host byte order to network byte order.
  • unsigned long htonl (unsigned long hostlong) : This function converts a 32-bit (4 byte) number from host byte order to network byte order.
  • unsigned short nightshirt (unsigned short nightshirt) : This function converts the 16 bits (2 byte) number in network byte order to host byte order.
  • unsigned long ntohl (unsigned long netlong) : This function converts a 32-bit number from network byte order to host byte order.

These functions are macros, and insert the source code into the calling program. On small endian machines, the code changes the value around the network byte order. On the big endian machine, there is no need to insert code, the function is defined as null.

Program to Determine Host Byte Order

Save the following code in the byteorder.c file, compile it and run it on the machine.

In this example, we store the 2-byte value 0x0102 in a short integer, checking the two consecutive bytes c [0] (address A) and c [1] (address A + 1) and the order byte.

The program generates output on the Pentium machine as follows.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Unix socket Topics