/*
 * an echo deamon by Cubbi
 *
 * (c) 1999 Sergey Zubkov
 */
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>

int main()
{
 int fd; // will be the listening socket's file handle
 int newfd; // will be the accepted connection's socket's file handle
 FILE* sockr;
 FILE* sockw;
 char c;

 struct sockaddr_in server;
 struct sockaddr_in host;
 socklen_t hostlen;
 struct hostent* he;
// char* name="localhost";  // <- hostname to connect
// char* errmsg;


 // Fill out the structures
 server.sin_family=AF_INET;
 server.sin_port=htons(4001);  // <- port
 server.sin_addr.s_addr=inet_addr("127.0.0.1"); // <- if you already
 //	know IP address, put it in there, and don't call gethostbyname
// if ((he=gethostbyname(name)))
//	memcpy(&server.sin_addr,he->h_addr,he->h_length);
// else {
//	fprintf(stderr,"no IP address for %s: %s\n",name,errmsg);
//	return -1;
// }
// fprintf(stderr,"trying %s at port %d\n",
//	inet_ntoa(server.sin_addr),(int)ntohs(server.sin_port));

 fd=socket(AF_INET,SOCK_STREAM,0);
 // now the socket exists in the name space, but is not assigned an address
 if(bind(fd,(struct sockaddr *)&server,sizeof(server))) {
	 perror("could not bind");
	 exit(-1);
 }
 // now the socket has an address
 listen(fd,5);
 // now the socket listens to incoming connections
 while(1) {
	newfd=accept(fd,(struct sockaddr *)&host,&hostlen); // get next connection
	if(!fork()) {
		//child
		sockr=fdopen(newfd,"r");
		sockw=fdopen(newfd,"w");
		while(!feof(sockr)) {
			c=fgetc(sockr);
			fflush(sockr);
			fputc(c,sockw);
			fflush(sockw);
		}
		exit(0);
	}
 }
}
