Data Manipulation Routines

There are several routines that convert values between network byte order and host (or local system) byte order. Windows Sockets offers byte-ordering routines for 16- and 32-bit values from both host byte order and network byte order. The htons() function takes a 16-bit value (a short), and converts it from host byte order to network byte order—hence the name htons (host to network short). The other byte-ordering functions available are htonl(), ntohs(), and ntohl().

There are two other useful routines offered by Windows Sockets which convert IP addresses between strings and network byte-ordered 32-bit values. These functions are inet_ntoa() and inet_addr(). These routines are useful to convert the IP address of an endpoint user input. In the following example, a TCP-based server application uses the inet_ntoa() function to log incoming connection attempts:


SOCKET             cli_sock,    srv_sock;
LPSOCKADDR_IN        cli_addr;
char             *cli_ip,     buf[MAX_BUF];
int             len;
.
/* Accept incoming connection, create new local socket cli_sock */

cli_sock=accept(srv_sock,(LPSOCKADDR)&cli_addr,&len);

if (cli_sock==INVALID_SOCKET){
    return(ERROR);
}

/* Convert endpoint IP address from network byte order to ASCII */

cli_ip=inet_ntoa(cli_addr.sin_addr);
sprintf(buf,"Incoming connection request from: %s.\n",cli_ip);
log_event(buf);