Other Socket Routines

Several other routines that simplify manipulating names and addresses are available. The following table summarizes the routines for manipulating variable-length byte strings and byte-swapping network addresses and values.

Table 7-2 Runtime Library Routines

Interface Synopsis

memcmp()

Compares byte-strings; 0 if same, not 0 otherwise. For more information, see the memcmp(3C) man page.

memcpy()

Copies n bytes from s2 to s1. For more information, see the memcpy(3C) man page.

memset()

Sets n bytes to value starting at base. For more information, see the memset(3C) man page.

htonl()

32-bit quantity from host into network byte order. For more information, see the htonl(3C) man page.

htons()

16-bit quantity from host into network byte order. For more information, see the htons(3C) man pages.

ntohl()

32-bit quantity from network into host byte order. For more information, see the ntohl(3C) man page.

ntohs()

16-bit quantity from network into host byte order. For more information, see the ntohs(3C) man page.

The byte-swapping routines are provided because the operating system expects addresses to be supplied in network order. On some architectures, the host byte ordering is different from network byte order, so programs must sometimes byte-swap values. Routines that return network addresses do so in network order. Byte-swapping problems occur only when interpreting network addresses. For example, the following code formats a TCP or UDP port:

printf("port number %d\n", ntohs(sp->s_port));

On systems that do not need these routines, the routines are defined as null macros.