#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>

#define SIZE sizeof(struct sockaddr_in)


void catcher(int sig);
int newsockfd;
void timeout(int nsig);

int ret,rt;
int allbytes;
time_t t,lastt;

main(){
    int sockfd;
    char c;
    struct sockaddr_in server = {AF_INET,7010};
    struct sockaddr_in client;    
    struct socklen_t *lengthp;
    static struct sigaction act;
    char *Ptxt="Hello from server !!!";
    char Pbuf[2048];
    char pbuffer[1024];
    int len;
    char e=(int)255;
    char *_;
    struct tm *tmp;

    
    act.sa_handler=catcher;
    sigfillset(&(act.sa_mask));
    sigaction(SIGPIPE,&act,NULL);

    printf("%s","Enter port :");
    if(fgets(pbuffer,sizeof(pbuffer),stdin)){
	server.sin_port = htons(atoi(pbuffer));	 
    } else {
        printf("%s  %s\n","Cannot connect with ",pbuffer);
	exit(1);
    };
    
    if(( sockfd= socket(AF_INET, SOCK_STREAM,0))==-1) exit(1);
    if(bind(sockfd, (struct sockaddr *)&server, SIZE) == -1) exit(1);
    if(listen( sockfd, 5)==-1) exit(1);
    printf("%s\n","--- SERVER HERE---");
    
    for(;;){
	if(( newsockfd= accept(sockfd, NULL,NULL))==-1) exit(1);
	
	len = sizeof(client);
	ret=getpeername (newsockfd, (struct sockaddr *)&client,&len);

	_=inet_ntoa(client.sin_addr.s_addr);
	printf("%s\n","Type Ctrl-C for exit");    
	printf("WE RECIEVED QUERY FROM %s:%d\n",_,client.sin_port);
	lastt = t = time(NULL);

//        printf("%s",">");
	rt=0;
	signal(SIGALRM,timeout);
	alarm(2);
	for(;;){
	    if((ret=recv(newsockfd,&Pbuf,2048,0))>0){
		    /*if(ret==1)
		    if(Pbuf[0]==(int)255){
			close(sockfd);
			exit(0);		
		    };*/
		    	    
		Pbuf[ret]=0x0;
		allbytes+=ret;
		
		//t = time(NULL);
	    };	    
	};

	//ret = send(sockfd,e,1,0);        
        close(newsockfd);
        exit(0);
    };
    close(newsockfd);
}
    
void catcher(int sig){
    close(newsockfd);
    exit(0);
}

void timeout(int nsig){
    printf("We receive %d bytes. Speed=%d B/s %d KB/s\n",allbytes,allbytes/(time(NULL)-lastt),(allbytes/(time(NULL)-lastt))/1024);		    
    lastt = time(NULL);
    signal(SIGALRM,timeout);
    alarm(2);
    allbytes=0;
};

