Go to the previous, next section.

Byte Order Conversion

Different kinds of computers use different conventions for the ordering of bytes within a word. Some computers put the most significant byte within a word first (this is called "big-endian" order), and others put it last ("little-endian" order).

So that machines with different byte order conventions can communicate, the Internet protocols specify a canonical byte order convention for data transmitted over the network. This is known as the network byte order.

When establishing an Internet socket connection, you must make sure that the data in the sin_port and sin_addr members of the sockaddr_in structure are represented in the network byte order. If you are encoding integer data in the messages sent through the socket, you should convert this to network byte order too. If you don't do this, your program may fail when running on or talking to other kinds of machines.

If you use getservbyname and gethostbyname or inet_addr to get the port number and host address, the values are already in the network byte order, and you can copy them directly into the sockaddr_in structure.

Otherwise, you have to convert the values explicitly. Use htons and ntohs to convert values for the sin_port member. Use htonl and ntohl to convert values for the sin_addr member. (Remember, struct in_addr is equivalent to unsigned long int.) These functions are declared in `netinet/in.h'.

Function: unsigned short int htons (unsigned short int hostshort)

This function converts the short integer hostshort from host byte order to network byte order.

Function: unsigned short int ntohs (unsigned short int netshort)

This function converts the short integer netshort from network byte order to host byte order.

Function: unsigned long int htonl (unsigned long int hostlong)

This function converts the long integer hostlong from host byte order to network byte order.

Function: unsigned long int ntohl (unsigned long int netlong)

This function converts the long integer netlong from network byte order to host byte order.

Go to the previous, next section.