TCP/IP Programming Manual

number of the socket created by your server program and the remote address and port number
passed from LISTNER).
The programming example on the following pages uses LISTNER to start a server:
#include <socket.h>
#include <in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
int Accept_Conn(char*);
int sock = -1;
int main(int argc, char *argv[])
{
int nrcvd;
char buf[1024], *cp;
/*
* If this has been started by a server, then
* accept a connection; otherwise, echo to
* stdout from stdin.
*/
if (argv[1] != (char *)NULL) {
/*
* argv[1] must have port.hostname format.
*/
if ((cp = strchr(argv [1], '.')) == (char *)NULL) {
fprintf(stderr, "Server: bad arg %s\n", argv[1]);
exit(1);
}
*cp = 0;
if (atoi(argv[1]) == 0) {
fprintf(stderr, "Server: bad arg %s\n", argv[1]);
exit(1);
}
*cp = '.';
if (Accept_Conn(argv[1]) == 0)
exit(1);
}
if (sock >= 0)
while ((nrcvd = recv(sock, buf, (int)sizeof(buf), 0)) > 0)
send(sock, buf, nrcvd, 0);
else
while ((nrcvd = read(fileno(stdin), buf, (int)sizeof(buf))) > 0)
write(fileno(stdout), buf, nrcvd);
exit(0);
}
/* Accept an incoming connection request.
* The argument passed to us in the form:
*
* PORT.HOST
*/
memset (&sin, 0, sizeof(sin));
int Accept_Conn(char* cp)
{
struct sockaddr_in sin;
/*
* Set up the sock_addr_in structure based on the
* argument.
*/
sin.sin_port = atoi (cp);
cp = strchr (cp, '.') + 1;
if ((sin.sin_addr.s_addr = inet_addr (cp)) == 0) {
printf ("Bad value for %s\n", cp);
38 Introduction to Programming to the Guardian Sockets Library