Codice: Seleziona tutto
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <string.h>
#define PORTA 4000
int operationwithclient(int);
int main(){
int sock,newsock,pid;
struct sockaddr_in my_addr;
struct sigaction signal;
socklen_t size;
char buffer[512];
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1){
printf("Errore con il socket");
exit(0);
}
my_addr.sin_addr.s_addr=INADDR_ANY;
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(PORTA);
if(bind(sock,(struct sockaddr*)&my_addr,sizeof(my_addr))==-1){
printf("Errore con il binding");
exit(0);
}
if(listen(sock,5)==-1){
printf("Errore con il listening");
exit(0);
}
printf("Attendo connessioni sulla porta %d\n",PORTA);
while(1){
size=sizeof(struct sockaddr_in);
struct sockaddr_in client_addr;
newsock=accept(sock,(struct sockaddr*)&client_addr,&size);
printf("Server: Ho una connessione da:%s\n",inet_ntoa(client_addr.sin_addr));
pid=fork();
if(pid!=0){//is parent
close(newsock);
continue;
}else{
operationwithclient(newsock);
exit(0);
}
}
close(newsock);// this function will come require only if the server termineted.
}
//FUNCTIONS----------------------------------------------------------------------------------------------------------------
operationwithclient(int socke){
char *passwordrequire="Password request: ";
char buffer[512];
char* name;
int len;
char password[]="Ciao";
char* welcomemessage="Benvenuto";
send(socke,passwordrequire,19,0);
recv(socke,buffer,sizeof(buffer),0);
printf("%s",buffer);
if(strncmp(buffer,password,4)==0){
printf("Permissed\n");
strcpy(buffer,"");
}else{
printf("not permissed\n");
return 0;
}
while(1){
//autenticate user
recv(socke,buffer,sizeof(buffer),0);
printf("%s %d",buffer,sizeof buffer);
if(strncmp(buffer,"exit",4)==0){
printf("Connesione chiusa con %d",socke);
close(socke);
break;
}
}
}