BSD Sockets Interface Programmer's Guide
Chapter 2 49
Using Internet Stream Sockets
Example Using Internet Stream Sockets
* demonstrate many of the features of sockets, as well as good
* conventions for using these features.
*
* This program provides 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 client will be running
* must also have the same entry (same port number) in its
* /etc/services file.
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <netdb.h>
int s; /* connected socket descriptor */
int ls; /* listen socket descriptor */
struct hostent *hp; /* pointer to host info for remote host */
struct servent *sp; /* pointer to service information */
long timevar; /* contains time returned by time() */
char *ctime(); /* declare time formatting routine */
struct linger linger = {1,1};
/* allow lingering, graceful close; */
/* used when setting SO_LINGER */
struct sockaddr_in myaddr_in; /* for local socket address */
struct sockaddr_in peeraddr_in;/* for peer socket address */
/*
* 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 listen socket, and for each incoming
* connection, it forks a child process to process the data.
* It will loop forever, until killed by a signal.
*/
main(argc, argv)
int argc;
char *argv[];
{
int addrlen;
/* clear out address structures */
memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));
memset ((char *)&peeraddr_in, 0, sizeof(struct sockaddr_in));
/* Set up address structure for the listen socket. */
myaddr_in.sin_family = AF_INET;
/* The server should listen 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