BSD Sockets Interface Programmer's Guide
54 Chapter 2
Using Internet Stream Sockets
Example Using Internet Stream Sockets
/* The port number must be converted first to
* host byte order before printing. On most hosts,
* this is not necessary, but the ntohs() call is
* included here so this program could easily
* be ported to a host that does require it.
*/
printf(”Completed %s port %u, %d requests, at %s\n”,
hostname, ntohs(peeraddr_in.sin_port), reqcnt,
ctime(&timevar));
}
/*
* C L I E N T . T C P
*
* This example program demonstrates the use of stream
* sockets as a BSD Sockets mechanism. This contains the client,
* and is intended to operate in conjunction with the server
* program found in serv.tcp. 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”. For it
* to function, an entry needs to exist in the /etc/services
* file. The port address for this service can be any port
* number that is not used, such as 22375, for example. The
* host on which the server 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 <stdio.h>
#include <netdb.h>
int s; /* connected 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 sockaddr_in myaddr_in; /* for local socket address */
struct sockaddr_in peeraddr_in; /* for peer socket address */
/*
* M A I N
*
* This routine is the client that requests service from the
* remote example server. It creates a connection, sends a few
* of requests, shuts down the connection in one direction to
* signal the server about the end of data, and then receives
* all of the responses. Status will be written to stdout.
*
* The name of the system to which the requests will be sent
* is given as a parameter to the command.
*/
main(argc, argv)