Code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctype.h>
#include <sys/socket.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#define MAXLENGTH 80
#define SERVERPORT 1313
void minuscolatore (int in,int out){
char inputline[MAXLENGTH];
int len,i;
while((len=recv(in,inputline,MAXLENGTH,0))>0){
for(i=0;i<len;i++){
inputline[i]=tolower(inputline[i]);
}
send(out,inputline,len,0);
}
}
void maiuscolatore(int in,int out){
char inputline[MAXLENGTH];
int len,i;
while((len=recv(in,inputline,MAXLENGTH,0))>0){
for(i=0;i<len;i++){
inputline[i]=toupper(inputline[i]);
}
if (strcmp(inputline,"FINE")==0){
exit(0);
}
send(out,inputline,len,0);
}
}
int main(){
int sock,client_len,fd;
char c;
struct sockaddr_in client, server = {AF_INET,htons(SERVERPORT),INADDR_ANY};
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1){
perror("Socket fallita");
exit(1);
}
if(bind(sock,(struct sockaddr *)&server,sizeof server)==-1){
perror("Bind fallita");
exit(2);
}
listen(sock,5);
while(1){
client_len=sizeof(client);
if((fd=accept(sock,(struct sockaddr *)&client,&client_len))<0){
perror("accept fallita");
exit(3);
}
if (recv(fd,&c,1,0)==-1){
perror("recv server fallita");
exit(4);
}
if (c=='+'){
switch(fork()){
case -1:
perror("Fork fallita");
exit(4);
case 0:
printf("Aperta connessione\n");
maiuscolatore(fd,fd);
printf("Chiusa connessione\n");
}
}
else if (c=='-'){
switch(fork()){
case -1:
perror("Fork fallita");
exit(4);
case 0:
printf("Aperta connessione\n");
minuscolatore(fd,fd);
printf("Chiusa connessione\n");
}
}
close(fd);
}
}