#include #include #include #include #include #include #define MSIZE 255 //lungimea maxima a mesajului #define PORT 12345 //portul la care asculta main() { int socketd,i,len_addr,sd; char msg[MSIZE],reply[MSIZE],s[MSIZE]; struct sockaddr_in sock,sock_client; struct hostent *hent; //construim un socket stream (orientat conexiune; TCP) pentru domeniul IPv4 //Internet Protocol (AF_INET) socketd=socket(AF_INET,SOCK_STREAM,0); printf("Creare socket socketd=%d\n",socketd); //curat continutul lui sock (scriu 0) memset((char *)&sock,0,sizeof(sock)); sock.sin_family=AF_INET; //domeniul Internet sock.sin_addr.s_addr=htonl(INADDR_ANY); //adresa IP la care asculta serverul (INADDR_ANY=oricare) sock.sin_port=htons(12345); //portul server //legam socketul de structura sock (rezervam portul in kernel) if( bind(socketd,(struct sockaddr *) &sock,sizeof(sock)) <0) { perror("Eroare la bind.\n"); exit(1); } //punem serverul in starea de asteptare de conexiuni listen(socketd,2); printf("Serverul asteapta conexiuni..\n"); while(1) { len_addr=sizeof(struct sockaddr); //am o conexiune ==> sd este descriptorul de socket pt conexiunea cu clientul sock_client sd=accept(socketd,(struct sockaddr *) & sock_client,&len_addr); printf("Am client.\n"); //pentru fiecare client cream un proces fiu care se va ocupa de el if(fork()==0) { i=recv(sd, msg, MSIZE,0); if(i>255 || i<=0) {close(sd); exit(1);} msg[i]='\0'; printf("Am primit de la client: %s\n",msg); //verificam daca mesajul de la client incepe cu "HELLO;" if (strstr(msg,"HELLO;")==msg) { strcpy(s,(char *) (msg+6)); strcpy(reply,"HELLO "); strcat(reply,s); strcat(reply,"! "); if (!(hent = gethostbyname ("127.0.0.1"))) {perror("Eroare la gethostbyname.\n"); exit(1);} strcat(reply,(char *)(char *)hent->h_name); strcat(reply," is pleased to meet you."); printf("Trimit la client: %s\n",reply); send(sd,reply,strlen(reply),0); } else { strcpy(reply,"200 Message not understood!"); send(sd,reply,strlen(reply),0); } close(sd); } } }