#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <strings.h>


/* Carles Pina i Estany - carles@pinux.info
 * Febrer 2004*/

void atendre (int newfd);

int main () {
	struct sockaddr_in servaddr;
	char jo[100];	
	int sockfd,newfd;
	struct sockaddr_in client_info;
	struct hostent *host;
	struct in_addr *ip;
	int port=7879;
	int pid_recullit;

	int temp;
	char nom_temp[100];
	pid_t pid;
	int addrlen;

	sockfd=socket(AF_INET,SOCK_STREAM,0);

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;

	gethostname(nom_temp,100);

	host=gethostbyname(nom_temp);
	ip=(struct in_addr*)host->h_addr;
	snprintf(jo,16,"%s",inet_ntoa(*ip));
	printf("%s\n",inet_ntoa(*ip));

	servaddr.sin_port=htons(port);

	temp=bind(sockfd,(struct sockaddr*)&servaddr,sizeof(struct sockaddr_in));
	if (temp!=0) {
		fprintf(stderr,"Bind fracassat\n");
		return (1);
	}
	listen (sockfd,10);
	addrlen=sizeof(struct sockaddr_in);

	for (;;) {
		bzero(&client_info,sizeof(client_info));
		printf("Esperant connexio\n");
		newfd=accept(sockfd,(struct sockaddr*)&client_info,&addrlen);
		fprintf(stderr,"Connectat client. IP: %s\n",inet_ntoa(client_info.sin_addr));

		pid=fork();
		if (pid==0) {
			//Sóc el fill
			close(sockfd);
			atendre(newfd);
		}
		close(newfd); //el pare no el necessita
		printf("netejo fills\n");
		pid_recullit=waitpid(-1,NULL,WNOHANG);
		printf("He recullit el pid: %d\n",pid_recullit);
	}
	return(0);
}

void atendre (int newfd) {
	char buffer[100];
	char temporal[100];
	int llegit;

	printf("Ja estic atenent al fill\n");

	snprintf(temporal,100,"Introdueix texte\n");
	write(newfd,temporal,strlen(temporal));

	llegit=read (newfd,buffer,sizeof(buffer));

	buffer[llegit]='\0';

	snprintf(temporal,100,"Has dit: %s\n",buffer);
	printf("Diré a client: %s\n",temporal);
	
	write(newfd,temporal,strlen(temporal));

	close(newfd);
	exit(0);
}
