Skip to content
Snippets Groups Projects
Select Git revision
  • 0ce767385eea01dad6c47c3229a29baffe44779c
  • master default protected
2 results

server.c

Blame
  • server.c 2.07 KiB
    # include <pthread.h>
    #include "server.h"
    #include "GETheader.h"
    #include "RESPheader.h"
    
    #define MAXUSER 5
    
    void* handleclient(void * newsockfd);
    
    int main(int argc, char *argv[]){
    	struct addrinfo info, *res, *p;
    	int sockfd, newsockfd;
    	struct sockaddr_storage clien_addr;
    	socklen_t clien_size;
    	if (argc <2){
    		fprintf(stderr,"ERROR, no port provided\n");//to check if there is no port provided at start
    		exit(1);
    	}
    	memset(&info, 0, sizeof(info));
    	info.ai_family = AF_UNSPEC; ///sets it to unspecified
    	info.ai_socktype = SOCK_STREAM; //TCP connection stream oriented
    	info.ai_flags = AI_PASSIVE; //listen on on all ip interface of machine
    	info.ai_protocol = 0; //set this to zero as default
    
    	if((getaddrinfo(NULL, argv[1], &info, &res) != 0)){
    		fprintf(stderr,"ERROR, no port provided\n");//to check if getaddrinfo gets any addrinfos
    		exit(1);
    	}
    
    	for (p = res; p!= NULL; p = p->ai_next)
    	{
    		if((sockfd = socket(p-> ai_family, p->ai_socktype, p->ai_protocol)) < 0){
    			perror("ERROR opening socket");
    			continue;
    		}
    
    		if ((bind(sockfd, p->ai_addr, p->ai_addrlen)) < 0){
    
    			perror("ERROR on binding");
    			continue;
    		}
    
    		break;
    	}
    
    	if (p == NULL)
    	{
    		perror("ERROR on creating and binding");
    		return 2;
    	}
    
    	if(listen(sockfd,MAXUSER)<0){
    		perror("ERROR listening");
    		return 2;
    	}
    
    
    	while(1){
    		clien_size = sizeof (clien_addr);
    
    		if((newsockfd = accept(sockfd, (struct sockaddr *) &clien_addr, &clien_size)) < 0){
    			perror("ERROR accepting");
    			return 3;
    		}
    
    		pthread_t tid;
    
    		if (pthread_create(&tid, NULL, handleclient, &newsockfd) <0)
    		{
    			perror("ERROR creating thread");
    			return 3;
    		}
    
    		pthread_detach(tid);
    
    	}
    
    
    
    	 return 0;
    
    
    
    }
    
    
    void* handleclient(void * newsockfd){
    	int *sockfd_ptr = (int*) newsockfd;
    	int numbytes;
    	int sockfd = *sockfd_ptr;
    	char buffer[BUFFERSIZE];
    	bzero(buffer, BUFFERSIZE);
    
    	if ((numbytes = recv(sockfd, buffer, 255, 0)) <0)
    	{
    		perror("ERROR recieving");
    		return NULL;
    	}
    	struct GET_header header;
    
    	parse_GET_request(buffer, &header);
    
    	if (sendresponse(sockfd, &header) <0)
    	{
    		perror("ERROR sending");
    		return NULL;
    	}
    
    	close(sockfd);
    }