BSD Sockets Interface Programmer's Guide
102 Chapter 4
Using Internet Datagram Sockets
Example Using Datagram Sockets
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
int s; /* socket descriptor */
#define BUFFERSIZE 1024 /* max size of packets to be received */
int cc; /* contains the number of bytes read */
char buffer[BUFFERSIZE]; /* buffer for packets to be read into */
struct hostent *hp; /* pointer to info of requested host */
struct servent *sp; /* pointer to service information */
struct sockaddr_in myaddr_in; /* for local socket address */
struct sockaddr_in clientaddr_in;/* for client's socket address */
struct in_addr reqaddr; /* for requested host's address */
#define ADDRNOTFOUND 0xffffffff /* return address for unfound host */
/*
* M A I N
*
* This routine starts the server. It forks, leaving the child
* to do all the work, so it does not have to be run in the
* background. It sets up the socket, and for each incoming
* request, it returns an answer. Each request consists of a
* host name for which the requester desires to know the
* internet address. The server will look up the name in its
* /etc/hosts file, and return the internet address to the
* client. An internet address value of all ones will be returned
* if the host name is not found. NOTE: This example is valid
* only if the /etc/hosts file is being used to lookup host names.
*
*/
main(argc, argv)
int argc;
char *argv[];
{
int addrlen;
/* clear out address structures */
memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));
memset ((char *)&clientaddr_in, 0, sizeof(struct sockaddr_in));
/* Set up address structure for the socket. */
myaddr_in.sin_family = AF_INET;
/* The server should receive on the wildcard address,
* rather than its own internet address. This is
* generally good practice for servers, because on
* systems which are connected to more than one
* network at once will be able to have one server
* listening on all networks at once. Even when the
* host is connected to only one network, this is good
* practice, because it makes the server program more
* portable.