Transport Interfaces Programming Guide

Other Routines

In addition to address-related database routines, there are several other routines that simplify manipulating names and addresses. Table 2-3 summarizes the routines for manipulating variable-length byte strings and byte-swapping network addresses and values.

Table 2-3 Runtime Library Routines

Call 

Synopsis 

memcmp(s1, s2, n)

Compares byte-strings; 0 if same, not 0 otherwise

memcpy(s1, s2, n)

Copies n bytes from s2 to s1

memset(base, value, n)

Sets n bytes to value starting at base

htonl(val)

32-bit quantity from host into network byte order 

htons(val)

16-bit quantity from host into network byte order 

ntohl(val)

32-bit quantity from network into host byte order 

ntohs(val)

16-bit quantity from network into host byte order 

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. There are byte-swapping problems 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 certain machines, where these routines are not needed, they are defined as null macros.