BSD Sockets Interface Programmer's Guide

106 Chapter 4
Using Internet Datagram Sockets
Example Using Datagram Sockets
struct in_addr reqaddr; /* for returned internet address */
#define ADDRNOTFOUND 0xffffffff /* value returned for unknown host */
#define RETRIES 5 /* # of times to retry before giving up */
/*
* H A N D L E R
*
* This routine is the signal handler for the alarm signal.
* It simply re-installs itself as the handler and returns.
*/
handler()
{
signal(SIGALRM, handler);
}
/*
* M A I N
*
* This routine is the client which requests service from
* the remote “example server”. It will send a message to the
* remote nameserver requesting the internet address corresponding
* to a given hostname. The server will look up the name, and
* return its internet address. The returned address will be
* written to stdout.
*
* The name of the system to which the requests will be sent is
* given as the first parameter to the command. The second
* parameter should be the name of the target host for which the
* internet address is sought.
*/
main(argc, argv)
int argc;
char *argv[];
{
int i;
int retry = RETRIES; /* holds the retry count */
char *inet_ntoa();
if (argc != 3) {
fprintf(stderr, ”Usage: %s <nameserver> <target>\n”,
argv[0]);
exit(1);
}
/* clear out address structures */
memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));
memset ((char *)&servaddr_in, 0, sizeof(struct sockaddr_in));
/* Set up the server address. */
servaddr_in.sin_family = AF_INET;
/* Get the host info for the server's hostname that the
* user passed in.
*/
hp = gethostbyname (argv[1]);
if (hp == NULL) {
fprintf(stderr, ”%s: %s not found in /etc/hosts\n”,
argv[0], argv[1]);