BSD Sockets Interface Programmer's Guide

Chapter 4 105
Using Internet Datagram Sockets
Example Using Datagram Sockets
sendto (s, &reqaddr, sizeof(struct in_addr),
0, &clientaddr_in, addrlen);
}
default: /* Parent process comes here. */
exit(0);
}
}
/*
* C L I E N T . U D P
*
* This is an example program that demonstrates the use of
* datagram sockets as an BSD Sockets mechanism. This contains
* the client, and is intended to operate in conjunction with the
* server program found in serv.udp. Together, these two programs
* demonstrate many of the features of sockets, as well as good
* conventions for using these features.
*
* This program requests a service called ”example”. In order for
* it to function, an entry for it needs to exist in the
* /etc/services file. The port address for this service can be
* any port number that is likely to be unused, such as 22375,
* for example. The host on which the server will be runnin
* must also have the same entry (same port number) in its
* /etc/services file.
*
* The ”example” service is an example of a simple name server
* application. The host that is to provide this service is
* required to be in the /etc/hosts file. Also, the host providing
* this service presumably knows the internet addresses of many
* hosts which the local host does not. Therefore, this program
* will request the internet address of a target host by name from
* the serving host. The serving host will return the requested
* internet address as a response, and will return an address of
* all ones if it does not recognize the host name.
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <signal.h>
#include <netdb.h>
extern int errno;
int s; /* socket descriptor */
struct hostent *hp; /* pointer to info for nameserver host */
struct servent *sp; /* pointer to service information */
struct sockaddr_in myaddr_in; /* for local socket address */
struct sockaddr_in servaddr_in;/* for server socket addres */