#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/param.h>
#include <errno.h>
#define ERROR(s) {fprintf(stderr,"%d-",errno); perror(s); return(-1);}
main (argc, argv)
int argc;
char *argv[];
{
struct sockaddr_in sa;
struct sockaddr_in caller;
int s, msgsock, length;
int retval;
char buf[BUFSIZ], acknowledgement[BUFSIZ];
if ((s = socket(AF_INET,SOCK_STREAM,0)) < 0)
ERROR ("socket");
/* name socket, register the socket */
sa.sin_family= AF_INET;
sa.sin_addr.s_addr = INADDR_ANY; /* not choosy about who calls */
sa.sin_port= 22222; /* this is our port number */
if (bind(s,(struct sockaddr_in *)&sa,sizeof sa) < 0)
ERROR ("bind"); /* bind address to socket */
/* get assigned port number and print it */
length = sizeof(sa);
if (getsockname(s, (struct sockaddr_in *)&sa, &length) < 0)
ERROR("getsockname");
/* listen for connections on a socket */
listen (s, 5);
/* Use accept to wait for calls to the socket. Accept returns
a new socket which is connected to the caller. msgsock will be a
temporary (non-resuable) socket different from s */
if ((msgsock = accept(s,(struct sockaddr *)&caller,&length)) < 0)
ERROR ("accept");
/* optional ack; demonstrates bidirectionality */
gethostname(buf, sizeof buf);
/* write into the msgsock; the "s" is _only_for_rendezvous_ */
if ( write ( msgsock, acknowledgement, sizeof acknowledgement ) < 1 )
perror(argv[0]);
/* read lines until the stream closes */
retval = 1;
while(retval !=0 ) {
bzero(buf, sizeof(buf));
if( (retval = read(msgsock, buf, sizeof(buf))) < 0)
perror("reading stream message");
if (retval == 0) printf("ending connectionn");
else printf("read-->%sn", buf);
}
close(msgsock);
close (s);
exit (0);
}