Chapter 7, Developing applications over TCP/IP using Internet sockets
Manipulating byte strings and handling byte swapping (Internet domain)

Manipulating byte strings and handling byte swapping (Internet domain)

To manipulate variable-length byte strings and byte swapping of network addresses and values, see the following run-time library routines:


C Run-Time Routines

 ------------------------------------------------------------
 Call                   Purpose
 ------------------------------------------------------------
 memcmp(s1,s2,n)        compare byte strings
 memcpy(s2,s1,n)        copy n bytes from s1 to s2
 memset(base,'\0',n)    zero-fill n bytes starting at base
 htonl(val)             convert 32-bit quantity from host
                        to network byte order
 htons(val)             convert 16-bit quantity from host
                        to network byte order
 ntohl(val)             convert 32-bit quantity from
                        network to host byte order
 ntohs(val)             convert 16-bit quantity from
                        network to host byte order

The byte-swapping routines are provided because the operating system expects addresses to be supplied in network order. Because the hardware architecture of some machines is different from network order, programs are sometimes required to byte swap quantities. The library routines which return network addresses provide them in network order so that they may simply be copied into the structures provided to the system. This implies that users should encounter the byte-swapping problem only when interpreting network addresses. For example, to print out an Internet port:

   printf("port number %d\n", ntohs(sp->s_port));
For some architectures these routines are defined as null macros. Nevertheless, using them makes programs more portable.