Ejemplo n.º 1
0
int main(int argc, char ** argv)
{
    int 	sockfd, 	n;
    char 	recvline[MAXLINE + 1];
    struct 	sockaddr_in	servaddr;
    struct 	in_addr		**pptr;
    struct 	in_addr		*inetaddrp[2];
    struct 	in_addr		inetaddr;
    struct 	hostent		*hp;
    struct 	servent		*sp;

    if( argc != 3 )
        err_quit("usage: daytimetcpcli1 <hostname> <service>");

    if( (hp = gethostbyname(argv[1])) == NULL )
    {
        if(inet_pton(AF_INET, argv[1], &inetaddr) == 0 )
            err_quit("hostname error for %s: %s", argv[1], hstrerror(h_errno));
        else
        {
            inetaddrp[0] = &inetaddr;
            inetaddrp[1] = NULL;
            pptr = inetaddrp;
        }
    }
    else
        pptr = (struct in_addr **)hp->h_addr_list;

    if( (sp = getservbyname(argv[2], "tcp")) == NULL )
        err_quit("getservbyname error for %s", argv[2]);

    for(; *pptr != NULL; ++pptr)
    {
        sockfd = Socket(AF_INET, SOCK_STREAM, 0);

        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = sp->s_port;
        memcpy(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));

        printf("trying %s\n", Sock_ntop((SA *)&servaddr, sizeof(servaddr)));

        if( connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) == 0)
            break;

        err_ret("connect error");
        Close(sockfd);
    }

    if( *pptr == NULL )
        err_quit("unable to connect");

    char str[] = "hello";
    Writen(sockfd, str, strlen(str));


    while( (n = read(sockfd, recvline, MAXLINE)) > 0)
    {
        recvline[n] = 0;
        Fputs(recvline, stdout);
    }

    exit(0);
}
Ejemplo n.º 2
0
int main(int argc,char *argv[])
{
    int i,j,maxi,listenfd,connfd,sockfd;
    int n;
    ssize_t nready,efd,res;
    char buf[MAXLINE],str[INET_ADDRSTRLEN];
    socklen_t clilen;
    struct sockaddr_in cliaddr,servaddr;

    struct epoll_event tep,ep[OPEN_MAX];

    listenfd = Socket(AF_INET,SOCK_STREAM,0);

    int opt = 1;
    //设置socket属性 取消2msl保护
    setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

    Listen(listenfd,128);

    efd = epoll_create(OPEN_MAX);
    if(efd == -1)
        perr_exit("epoll_create");
    tep.events = EPOLLIN;//读数据
    tep.data.fd = listenfd;
    res = epoll_ctl(efd,EPOLL_CTL_ADD,listenfd,&tep);
    if(res == -1)
        perr_exit("epoll_ctl");

    for(;;)
    {
        nready = epoll_wait(efd,ep,OPEN_MAX,-1);
        //阻塞监听
        if(nready == -1)
            perr_exit("epoll_wait");
        for(i = 0; i < nready; ++i)
        {
            if(!(ep[i].events & EPOLLIN))//不是读事件跳过
                continue;
            if(ep[i].data.fd == listenfd)
            {
                clilen = sizeof(cliaddr);
                connfd = Accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
                printf("received from %s at PORT\n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,str,sizeof(str)));
                tep.events = EPOLLIN;
                tep.data.fd = connfd;
                res = epoll_ctl(efd,EPOLL_CTL_ADD,connfd,&tep);
                if(res == -1)
                    perr_exit("epoll_ctl");
            }
            else 
            {
                sockfd = ep[i].data.fd;
                n = Read(sockfd,buf,MAXLINE);
                if(n <= 0)
                {
                    res = epoll_ctl(efd,EPOLL_CTL_DEL,sockfd,NULL);
                    if(res == -1)
                        perr_exit("epoll_ctl");
                    Close(sockfd);
                    printf("client[%d] closed connection\n",j);
                }
                else
                {
                    for(j = 0; j < n; ++j)
                        buf[j] = toupper(buf[j]);
                    Writen(sockfd,buf,n);
                }
            }
        }
    }
    Close(listenfd);
    Close(efd);
    return 0;
}
Ejemplo n.º 3
0
int main (int argc, char *argv[])
{
    	int tuttoOK=1;
    	short int local_port_number;
    	int listenfd[3], connectedfd[3], socketfd, ris, i, nwrite, nread, n;
    	struct sockaddr_in Cli;
	int *intptr;
	pthread_t thid[10];
	/*pthread_attr_t attr;*/
	unsigned int len;
	char buflettura[LENVETLETTURA];
	char bufscrittura[LENVETSCRITTURA];
	int sum, sumlettura;

	if    ( (sizeof(int)!=sizeof(long int)) ||  (sizeof(int)!=4)  )
	{
		printf ("dimensione di int e/o long int != 4  -> TERMINO\n");
		fflush(stdout);
		exit(1);
	}

    	if (argc != 2)
	{
		printf ("necessario 1 parametro\n");
		usage ();
		exit (1);
    	}
    	else
    	{
		local_port_number = atoi (argv[1]);
    	}
	
	init_random();

	if( ! Init_TCP_Session_Module(NULL) )
	{
		printf ("Init_TCP_Session_Module() failed\n");
		fflush(stdout);
		exit(1);
	}

	for(i=0;i<2;i++)
	{
		ris=TCPS_setup_socket_listening( listenfd+i, local_port_number+i);
		if (!ris)
		{	
			printf ("setup_socket_listening() failed\n");
			exit(1);
		}
	}
	ris=TCP_setup_socket_listening( listenfd+2, local_port_number+2);
	if (!ris)
	{	
		printf ("setup_socket_listening() failed\n");
		exit(1);
	}

	/*sleep(50);*/

	ris= TCP_setup_connection(&socketfd, "127.0.0.1", local_port_number+2);
	if (!ris)  {
		printf ("impossibile connettersi al server: TERMINO!!\n" );
		fflush(stdout);
		exit(1);
	}

	/*
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
	*/

	for(i=0;i<3;i++)
	{
		intptr=malloc(sizeof(int));
		if(intptr==NULL) { perror("malloc failed: "); fflush(stderr); exit(1); }

		/* wait for connection request */
		memset (&Cli, 0, sizeof (Cli));
		len = sizeof (Cli);
		for(;;)
		{
			printf ("Accept()\n");
			*intptr = Accept (listenfd[i], (struct sockaddr *) &Cli, &len);
			if (*intptr == SOCKET_ERROR)
			{
				if(errno==EINTR) continue;
				else
				{
					printf ("Accept() failed, Err: %d \"%s\"\n", errno,
					strerror (errno));
					exit (1);
				}
			}
			else
			{
				connectedfd[i]=*intptr;
				/*printf("fd_accept server %d \n", connectedfd[i]);*/
				/*ris=pthread_create(&(thid[i]), &attr, (ptr_thread_routine) &thread_For_Read_Write, (void *) intptr );*/
				ris=pthread_create(&(thid[i]), NULL, (ptr_thread_routine) &thread_For_Read_Write, (void *) intptr );
				if(ris)
				{
					/*
					Close(*intptr);
					Close(listenfd[i]);
					free(intptr);
					*/
					fprintf (stdout, "pthread_create( For_Read_Write ) failed, Err: %d \"%s\"\n", errno,strerror(errno));
					exit(2);
				}
				else
				{
					printf ("pthread_create succeed\n");
					break;
				}
			} /* fine creazione threads */
		} /* fine for(;;) */
	} /* for(i=0;i<3;i++) */

	for(i=0;i<2;i++)
	{
		ris=pthread_join( thid[i] , (void*) &intptr );
		if(ris!=0){
			printf("pthread_join( %d) failed: error=%d\n", i, ris );
			exit(-1);
		}
		else
		{
			if(intptr==NULL)
			{
				printf("pthread failed: malloc error\n");
				fflush(stdout);
				tuttoOK=0;
				exit(-1);
			}
			else if(*intptr==0)
			{
				printf("pthread failed: network error\n");
				fflush(stdout);
				tuttoOK=0;
				exit(-1);
			}
			else
				printf("pthread ok\n");
			fflush(stdout);
		}
	}

	/* parte client del socket tcp normale */
	nread=sizeof(int);
	/*printf("nread= %d", nread);*/
	printf ("Readn() sum \n");
	fflush (stdout);

	n = Readn (socketfd, (char*) &(sum), nread);
	if (n != nread)
	{
		printf ("Readn() sum failed \n");
		fflush(stdout);
		return (0);
	}
	sum=ntohl(sum);

	/* scrittura sul socket tcp normale */
	nwrite = LENVETSCRITTURA;
	printf ("Writen()\n");
	fflush (stdout);

	n = Writen (socketfd, bufscrittura, nwrite );
	if (n != nwrite)
	{
		printf ("Writen() failed \n");
		fflush(stdout);
		return (0);
	}
	/* lettura dal socket tcp normale*/
	nread=LENVETLETTURA;
	n = Readn (socketfd, buflettura, nread);
	if (n != nread)
	{
		printf ("Readn() main failed \n");
		fflush(stdout);
		return (0);
	}
	sumlettura=sommavet(buflettura,LENVETLETTURA);
	printf("somma spedita %d  somma calcolata %d\n", sum, sumlettura );
	fflush (stdout);
	/*
	stampavet(buflettura,LENVETLETTURA);
	fflush (stdout);
	*/
	if(sumlettura!=sum)
	{
		printf ("\033[33;35;1m somma del tcp errata: errore in trasmissione dati\n \033[0m ");
		fflush(stdout);
		return (0);
	}

	/* fine parte client del socket tcp normale */

	/* attesa thread che ha gestito il server con il socket tcp normale */
	ris=pthread_join( thid[2] , (void*) &intptr );
	if(ris!=0){
		printf("pthread_join( 2) failed: error=%d\n", ris );
		exit(-1);
	}
	else
	{
		if(intptr==NULL)
		{
			printf("pthread failed: malloc error\n");
			tuttoOK=0;
		}
		else if(*intptr==0)
		{
			printf("pthread failed: network error\n");
			tuttoOK=0;
		}
		else
			printf("pthread ok\n");
		fflush(stdout);
	}

	for(i=0;i<3;i++) {
		Close (connectedfd[i]);
		Close (listenfd[i]);
	}
	Close (socketfd);

    	printf ("Fine main\n");
	if(tuttoOK==0)
	{
    		printf ("\033[33;35;1m C'e' stato un errore di comunicazione\n \033[0m \n");
		fflush(stdout);
		exit(1);
	}
	if( ! Close_TCP_Session_Module(NULL) )
	{
		printf ("\033[33;35;1m Close_TCP_Session_Module() failed\n \033[0m ");
		fflush(stdout);
		exit(1);
	}
	
    	printf ("Tutto OK\n");
	fflush(stdout);
	return (0);
}
Ejemplo n.º 4
0
//程序主体
void proxy(int is_n, int listenfd) {
        struct sockaddr_in client_addr = { 0 };
        int serverfd = 0;
        int clientfd = 0;
        int client_len = 0;

        while (1) {
                //跟web服务器建立连接
                client_len = sizeof(struct sockaddr_in);
                clientfd = accept(listenfd, (struct sockaddr_in*) &client_addr,
                                &client_len);
                if (clientfd < 0) {
                        LOG_ERR("accept error:");
                        continue;
                }
                if (is_n) { //连接次级代理服务器
                        struct hostent *he;
                        he = gethostbyname(server_name);
                        serverfd =
                                        get_conn_socket(
                                                        inet_ntoa(
                                                                        *((struct in_addr *) he->h_addr_list[0])),
                                                        server_port);
                        if (serverfd == NULL ) {
                                LOG_ERR("connect to server error:");
                                close(clientfd);
                                continue;
                        }
                        int ret = fork();
                        if (ret < 0) {
                                LOG_MSG("无法建立新进程!\n");
                                fflush(stdout);
                                close(serverfd);
                                close(clientfd);
                                break;
                        } else if (ret == 0) {
                                close(listenfd);
                                //建立二次子进程,防止僵尸进程
                                ret = fork();
                                if (ret < 0) {
                                        close(serverfd);
                                        close(clientfd);
                                        _exit(0);
                                } else if (ret == 0) {
                                        readtpipe(clientfd, serverfd);
                                        _exit(0);
                                }
                                ret = fork();
                                if (ret < 0) {
                                        close(serverfd);
                                        close(clientfd);
                                        _exit(0);
                                } else if (ret == 0) {
                                        readtpipe(serverfd, clientfd);
                                        _exit(0);
                                }
                                close(serverfd);
                                close(clientfd);
                                _exit(0);
                        }
                        close(serverfd);
                        close(clientfd);
                        waitpid(ret, NULL, 0);
                } else {
                        //读取第一行,解析服务器host
                        recv(clientfd, line, 100, 0);
                        parse_cmd_http(line);
                        printf("%s  ---  >%s\n",
                                        inet_ntoa(client_addr.sin_addr),
                                        server_name);
                        struct hostent *he;
                        he = gethostbyname(server_name);
                        serverfd =
                                        get_conn_socket(
                                                        inet_ntoa(
                                                                        *((struct in_addr *) he->h_addr_list[0])),
                                                        server_port);
                        if (serverfd == NULL ) {
                                perror("connect to server error:");
                                close(clientfd);
                                continue;
                        }
                        int ret = fork();
                        if (ret < 0) {
                                LOG_MSG("无法建立新进程!\n");
                                fflush(stdout);
                                close(serverfd);
                                close(clientfd);
                                break;
                        } else if (ret == 0) {
                                close(listenfd);
                                //建立二次子进程,防止僵尸进程
                                ret = fork();
                                if (ret < 0) {
                                        close(serverfd);
                                        close(clientfd);
                                        _exit(0);
                                } else if (ret == 0) {

                                        Writen(serverfd, line, strlen(line));
                                        readtpipe(clientfd, serverfd);
                                        _exit(0);
                                }
                                ret = fork();
                                if (ret < 0) {
                                        close(serverfd);
                                        close(clientfd);
                                        _exit(0);
                                } else if (ret == 0) {
                                        readtpipe(serverfd, clientfd);
                                        _exit(0);
                                }
                                close(serverfd);
                                close(clientfd);
                                _exit(0);
                        }
                        close(serverfd);
                        close(clientfd);
                        waitpid(ret, NULL, 0);
                }

        }
}
Ejemplo n.º 5
0
void
str_echo(int sockfd)
{
	long		arg1;
	ssize_t		n;
	char		line[MAXLINE];

	for ( ; ; ) {
		if ( (n = Readline(sockfd, line, MAXLINE)) == 0)
			return;		/* connection closed by other end */
		if (sscanf(line, "%ld", &arg1) == 1) {
			if(arg1 == 0) {
				snprintf(line, sizeof(line), "%ld\n", arg1);
				printf("Client closed\n");
			} else {
				if(arg1 < 1 || arg1 > 10) 
					snprintf(line, sizeof(line), "input not in [1, 10]\n");	
				else{
					//snprintf(temp, sizeof(temp), "%ld\n", arg1);
					switch(arg1) {
						case 1:
						snprintf(line, sizeof(line), "mot\n");
						break;
						case 2:
						snprintf(line, sizeof(line), "hai\n");
						break;
						case 3:
						snprintf(line, sizeof(line), "ba\n");
						break;
						case 4:
						snprintf(line, sizeof(line), "bon\n");
						break;
						case 5:
						snprintf(line, sizeof(line), "nam\n");
						break;
						case 6:
						snprintf(line, sizeof(line), "sau\n");
						break;
						case 7:
						snprintf(line, sizeof(line), "bay\n");
						break;
						case 8:
						snprintf(line, sizeof(line), "tam\n");
						break;
						case 9:
						snprintf(line, sizeof(line), "chin\n");
						break;
						case 10:
						snprintf(line, sizeof(line), "muoi\n");
						break;
					}

				}
			}
		}
		else 
			snprintf(line, sizeof(line), "input error\n");

		n = strlen(line);
		Writen(sockfd, line, n);
		
	}
}
Ejemplo n.º 6
0
/**
 * struct sockaddr_in serv: 
 *
 * Descriptions
 **/
void
call_tcp(struct sockaddr_in servaddr, bool require_echo, unsigned expected_size,
    unsigned *latency, size_t *received)
{
    int sockfd;
    char buf[BUF_SIZE];

    struct timespec start;
    struct timespec end;
    int optval=1;

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if (setsockopt(sockfd, IPPROTO_IP, TCP_NODELAY, &optval, sizeof(optval)) != 0)
        perror("setsockopt TCP_NODELAY");
    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
        perror("connect");

    struct timespec wait_for_server={.tv_sec=0, .tv_nsec=INTERVAL};
    nanosleep(&wait_for_server, NULL);

    Writen(sockfd, &expected_size, sizeof(unsigned));
    Writen(sockfd, &require_echo, sizeof(bool));
    // could ignore the header time
    clock_gettime(CLOCK_MONOTONIC, &start);
    Writen(sockfd, buf, expected_size);
    if (DEBUG) printf("buf sent\n");
    if (require_echo) {
        // measuring latency
        Readn(sockfd, buf, expected_size);
        clock_gettime(CLOCK_MONOTONIC, &end);
        *latency = ((end.tv_sec - start.tv_sec) * 1000000000 +
            end.tv_nsec - start.tv_nsec) / 2;
    } else {
        // measuring througput
        Readn(sockfd, received, sizeof(received));
        clock_gettime(CLOCK_MONOTONIC, &end);
        *latency = ((end.tv_sec - start.tv_sec) * 1000000000 +
            end.tv_nsec - start.tv_nsec);
    }
    close(sockfd);
}


void
call_udp(struct sockaddr_in servaddr, bool require_echo, unsigned expected_size,
    unsigned *latency, size_t *received)
{
    int sockfd;
    char buf[BUF_SIZE];

    struct timespec start;
    struct timespec end;

    struct SimpleProtocol data;

    data.require_echo = require_echo;
    data.expected_size = expected_size;

    sockfd=socket(AF_INET, SOCK_DGRAM, 0);

    Sendton(sockfd, &data, sizeof(data), 0,
        (struct sockaddr *)&servaddr, sizeof(servaddr));
    clock_gettime(CLOCK_MONOTONIC, &start);
    Sendton(sockfd, buf, expected_size, 0,
        (struct sockaddr *)&servaddr, sizeof(servaddr));
    if (DEBUG) printf("request sent: expected_size=%u, require_echo=%i,  Reading...\n",
        data.expected_size, data.require_echo);
    if (data.require_echo) {
        // measuring latency
        // prevent client from blocking on receiving less data than expected
        setNonblocking(sockfd);
        Readn(sockfd, buf, expected_size);
        clock_gettime(CLOCK_MONOTONIC, &end);
        *latency = ((end.tv_sec - start.tv_sec) * 1000000000 +
            end.tv_nsec - start.tv_nsec) / 2;
    } else {
        // measuring througput
        Readn(sockfd, received, sizeof(int));
        clock_gettime(CLOCK_MONOTONIC, &end);
        *latency = ((end.tv_sec - start.tv_sec) * 1000000000 +
            end.tv_nsec - start.tv_nsec);
        if (DEBUG) printf("SUMMARY: %i of %u sent\n", *received, expected_size);
    }
    close(sockfd);
}
Ejemplo n.º 7
0
static void
write_string(int connfd, const char *string)
{
	Writen(connfd, string, strlen(string));
}
Ejemplo n.º 8
0
int main(int argc, char* argv[]) {

	if (argc < 6) {
		fprintf(stderr, "usage: %s [ msgbytes ] [ host ] [ port ] [ protocol ] [ numTrials ]\n",argv[0]);
		exit(-1);
	}

	int msgbytes = atoi(argv[1]);
	char *host = argv[2];
	int port = atoi(argv[3]);		     // protocol port number		
	char *prot = argv[4];
	int numTrials = atoi(argv[5]);

	if (port <= 0) {	
		fprintf(stderr,"PINGPONG: bad port number %s\n",argv[3]);
		exit(1);
	}

	if(msgbytes < 1 || msgbytes > 65000) {
		fprintf(stderr,"PINGPONG: bad msgbytes size (%d), 0 < msgbytes < 65001\n", msgbytes);
		exit(1);
	}

	if(numTrials < 0 || numTrials > 1000000) {
		fprintf(stderr, "PINGPONG: bad numTrials (%d) , 0 < numTrials < 1001\n", numTrials);
		exit(1);
	}
	
	struct addrinfo *serverptr;
	struct addrinfo hint;

	//  prepare the hint information
	bzero(&hint, sizeof(hint));
	hint.ai_flags = AI_CANONNAME;
	hint.ai_family = AF_INET;

	Getaddrinfo(host, NULL, &hint, &serverptr);
	
	struct timeval start, end;

	double times [numTrials];
	int i;

	if(strncmp(prot,"UDP", 3) == 0 ) {

		for(i = 0; i < numTrials; i++) {
			gettimeofday(&start, NULL);

			struct sockaddr_in cad; // structure to hold an IP address	

			struct sockaddr_in sad; // structure to hold an ip address	
			memset((char *)&sad,0,sizeof(sad)); // clear sockaddr structure	
			sad.sin_family = AF_INET;	      // set family to internet	
			bcopy(serverptr->ai_addr, (char *) &sad,  serverptr->ai_addrlen);
			sad.sin_port = htons((u_short)port);

			struct sockaddr_in sad2; // structure to hold an ip address	
			memset((char *)&sad2,0,sizeof(sad2)); // clear sockaddr structure	
			sad2.sin_family = AF_INET;	      // set family to internet	
			sad2.sin_addr.s_addr = htonl(INADDR_ANY);
			sad2.sin_port = htons((u_short)port+1);

//			printsin(&sad, "PRINT"," SIN:");
			
			fflush(stdout);
			
			int fsize = sizeof(struct sockaddr);
			int bytes_expected, sd;
			sd = Socket(AF_INET, SOCK_DGRAM, 0);

			Bind(sd, (struct sockaddr *) &sad2, sizeof(sad2));
			int *msg = malloc(msgbytes);
			int *dump = malloc(msgbytes);

//	fprintf(stderr,"PINGPONG: UDP Socket created\n");
//	fprintf(stderr,"PINGPONG: Sending a (%d) sized datagram\n", msgbytes);	

			Sendto(sd, &msgbytes, sizeof(msgbytes), 0,(struct sockaddr *) &sad, sizeof(sad));
			Sendto(sd, msg, sizeof(msg), 0, (struct sockaddr *) &sad, sizeof(sad));

//	fprintf(stderr,"PINGPONG: Datagram sent\n");
//	fprintf(stderr,"PINGPONG: Awaiting the response\n");

			Recvfrom(sd, &bytes_expected, sizeof(bytes_expected),0,(struct sockaddr *)  &cad, (socklen_t *) &fsize);
			Recvfrom(sd, dump, sizeof(dump),0,(struct sockaddr *) &cad, (socklen_t *) &fsize);

			gettimeofday(&end, NULL);			
			times[i] = elapsed(end,start);

//	fprintf(stderr,"PINGPONG: UDP received a %d size packet\n", bytes_expected);
			close(sd);
		}
//		fprintf(stderr,"PINGPONG: Execution done terminating\n");

	} else if(strncmp(prot,"TCP", 3) == 0) {
		char	buf[msgbytes];	     // buffer for data from the server
		for(i = 0; i < msgbytes; i++)
			buf[i] = 'A';
		buf[msgbytes-1] = 0;


		for(i = 0; i < numTrials; i++) {
			gettimeofday(&start, NULL);
			struct sockaddr_in sad; // structure to hold an IP address	
			memset((char *)&sad,0,sizeof(sad)); // clear sockaddr structure	
			sad.sin_family = AF_INET;	      // set family to Internet	
			bcopy(serverptr->ai_addr, (char *) &sad, serverptr->ai_addrlen);
			sad.sin_port = htons((u_short)port);

			int	sd;		   			
			sd = Socket(AF_INET, SOCK_STREAM, 0);

//			fprintf(stderr,"PINGPONG: Connecting to reflector TCP\n");

			Connect(sd, (struct sockaddr *) (&sad), sizeof(struct sockaddr));

//			fprintf(stderr,"PINGPONG: TCP connection established\n");

//			fprintf(stderr,"PINGPONG: Sending a message\n");
//			fprintf(stderr,"PINGPONG: Sending a message (%d) '%s'\n", msgbytes, buf);

			Writen(sd, &msgbytes, sizeof(int));
			Writen(sd, buf, msgbytes);

//			fprintf(stderr,"PINGPONG: Awating respone\n");

			Readn(sd, &msgbytes, sizeof(int));
			Readn(sd, buf, msgbytes);

//			fprintf(stderr,"PINGPONG: Recieved message (%d) '%s'\n", msgbytes, buf);
//			fprintf(stderr,"PINGPONG: Received response terminated\n");

			gettimeofday(&end, NULL);			
			times[i] = elapsed(end,start);


			close(sd);		
		}
	} else {
//		fprintf(stderr,"Improper protocol %s expecting either 'TCP' or 'UDP'\n", argv[2]);
	}


	double average = 0;

	for(i = 0; i < numTrials; i++)
		average += times[i];
	average /= numTrials;

	double stdDev = 0;

	for(i = 0; i < numTrials; i++)
		stdDev += (times[i] - average) * (times[i] - average);

	stdDev /= numTrials;
	stdDev = sqrt(stdDev);

	double error = 1.96 * (stdDev / sqrt(numTrials-1));

//	fprintf(stderr,"PINGPONG: Average of %d trials is %f\n", numTrials, average);
//	fprintf(stderr,"PINGPONG: Standard Deviation is %f\n", stdDev);
//	fprintf(stderr,"PINGPONG: Error is %f\n", error);

	printf("%d %f %f\n", msgbytes, average, error);

	return 1;
}
void server_multiProcess(){

    int maxi;//存储最大数组下标,记录连接数组的最大值
    int connfd; //用于存储连接的描述符
    int listenfd; //用于存放监听的描述符
    int sockfd; //监听套接字
    int clilen;
    int maxfd;
    int nready;
    fd_set rset,allset;    //
    char recvbuf[MAXLINE];
    int client[FD_SETSIZE];
    struct sockaddr_in cliaddr,servaddr;
    listenfd=Socket(AF_INET,SOCK_STREAM,0);
    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family=AF_INET;
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
    servaddr.sin_port=htons(SERV_PORT);
    Bind(listenfd,(SA*)&servaddr,sizeof(servaddr));
    Listen(listenfd,LISTENQ);
    maxfd=listenfd;
    maxi=-1;
    for(int i=0;i<FD_SETSIZE; i++){
        client[i]=maxi;
    }
    FD_ZERO(&allset);
    FD_SET(listenfd,&allset);
    while(1){
        rset=allset;
        nready=select(maxfd+1,&rset,NULL,NULL,NULL);
        if(FD_ISSET(listenfd,&rset)){
            int i;
            socklen_t clilen=sizeof(cliaddr);
            connfd=Accept(listenfd,(SA*)&cliaddr,&clilen);
            for(i=0;i<FD_SETSIZE;i++){
                if(client[i]<0){
                    client[i]=connfd;
                    break;
                }
            }
            if(i==FD_SETSIZE){
                err_quit("the number of client greater then FD_SETSIZE");
            }
            FD_SET(connfd,&allset);
            if(connfd>maxfd){
                maxfd=connfd;
            }
            if(i>maxi){
                maxi=i;
            }
            if(--nready<=0)
                continue;

        }

        for(int i=0;i<=maxi; i++){
            if((sockfd=client[i])<0)
                continue;
            if(FD_ISSET(sockfd,&rset)){
                int n;
                memset(recvbuf,0,MAXLINE);
                if((n=read(sockfd,recvbuf,MAXLINE))==0){
                    Close(sockfd);
                    FD_CLR(sockfd,&rset);
                    client[i]=-1;
                }else{
                    printf("%s\n",recvbuf);
                    Writen(sockfd,recvbuf,n);
                }

                if(--nready<0)
                    break;
            }
        }
    }

}
Ejemplo n.º 10
0
int
test_server_select(int argc, char **argv)
{
    int 					i, maxi, maxfd, listenfd, connfd, sockfd, nready,
    						client[FD_SETSIZE];
    char					buf[MAX_SIZE];
    fd_set					rset, allset;
    ssize_t					n;
    socklen_t				clilen;
    struct sockaddr_in		cliaddr, servaddr;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(PORT);

    Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    Listen(listenfd, 5);

    maxfd = listenfd;
    maxi = -1;
    for (i = 0; i < FD_SETSIZE; i++)
    	client[i] = -1;
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);

    while (1) {
    	rset = allset;
    	/*
    	 * 阻塞于select调用
    	 */
    	nready = Select(maxfd + 1, &rset, NULL, NULL, NULL);

    	if (FD_ISSET(listenfd, &rset)) {
    		clilen = sizeof(cliaddr);
    		connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);

    		for (i = 0; i < FD_SETSIZE; i++)
    			if (client[i] < 0) {
    				client[i] = connfd;
    				break;
    			}
    		if (i == FD_SETSIZE)
    			err_sys("too many clients");

    		FD_SET(connfd, &allset);
    		if(connfd > maxfd)
    			maxfd = connfd;
    		if(i > maxi)
    			maxi = i;

    		if(--nready <= 0)
    			continue;
    	}

    	for (i = 0; i < maxi; i++) {
    		if ( (sockfd = client[i]) < 0)
    			continue;
    		if (FD_ISSET(sockfd, &rset)) {
    			/*
    			 * 此处不应该阻塞于单个客户端的read调用,这样容易受到拒绝服务型攻击
    			 */
    			if ( (n = Read(sockfd, buf, MAX_SIZE)) == 0) {
    				/*
    				 * 套接字关闭时
    				 */
    				Close(sockfd);
    				FD_CLR(sockfd, &allset);
    				client[i] = -1;
    			} else
    				Writen(sockfd, buf, n);
    		}

    		if (--nready <= 0)
    			break;
    	}
    }

    return 0;
}
Ejemplo n.º 11
0
int
test_server_poll(int argc, char **argv)
{
	int 				i, maxi, listenfd, connfd, sockfd, nready;
	char 				buf[MAX_SIZE];
	ssize_t 			n;
	socklen_t 			clilen;
	struct pollfd 		client[OPEN_MAX];
	struct sockaddr_in 	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(PORT);

	Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

	Listen(listenfd, 5);

	client[0].fd 		= listenfd;
	client[0].events	= POLLRDNORM;
	for (i = 1; i < OPEN_MAX; i++)
		client[i].fd = -1;
	maxi = 0;

	while (1) {
		nready = Poll(client, maxi + 1, INFTIM);

		if (client[0].revents & POLLRDNORM) {
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);

			for (i = 1; i < OPEN_MAX; i++)
				if (client[i].fd < 0) {
					client[i].fd = connfd;
					break;
				}
			if (i == OPEN_MAX)
				err_sys("too many clients");

			client[i].events = POLLRDNORM;
			if (i > maxi)
				maxi = i;

			if (--nready <= 0)
				continue;
		}

		for (i = 1; i <= maxi; i++) {
			if ( (sockfd = client[i].fd) < 0)
				continue;
			if (client[i].revents & (POLLRDNORM | POLLERR)) {
				if ( (n = read(sockfd, buf, MAX_SIZE)) < 0) {
					if (errno == ECONNRESET) {
						Close(sockfd);
						client[i].fd = -1;

					} else
						err_sys("read error");
				} else if (n == 0) {
					Close(sockfd);
					client[i].fd = -1;
				} else
					Writen(sockfd, buf, n);

				if (--nready <= 0)
					break;
			}
		}
	}

	return 0;
}
Ejemplo n.º 12
0
int
main(int argc, char **argv)
{
	int					i, maxi, listenfd, connfd, sockfd;
	int					nready;
	ssize_t				n;
	char				line[MAXLINE];
	socklen_t			clilen;
	struct pollfd		client[OPEN_MAX];
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	client[0].fd = listenfd;
	client[0].events = POLLRDNORM;
	for (i = 1; i < OPEN_MAX; i++)
		client[i].fd = -1;		/* -1 indicates available entry */
	maxi = 0;					/* max index into client[] array */
/* end fig01 */

/* include fig02 */
	for ( ; ; ) {
		nready = Poll(client, maxi+1, INFTIM);

		if (client[0].revents & POLLRDNORM) {	/* new client connection */
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef	NOTDEF
			printf("new client: %s\n", Sock_ntop((SA *) &cliaddr, clilen));
#endif

			for (i = 1; i < OPEN_MAX; i++)
				if (client[i].fd < 0) {
					client[i].fd = connfd;	/* save descriptor */
					break;
				}
			if (i == OPEN_MAX)
				err_quit("too many clients");

			client[i].events = POLLRDNORM;
			if (i > maxi)
				maxi = i;				/* max index in client[] array */

			if (--nready <= 0)
				continue;				/* no more readable descriptors */
		}

		for (i = 1; i <= maxi; i++) {	/* check all clients for data */
			if ( (sockfd = client[i].fd) < 0)
				continue;
			if (client[i].revents & (POLLRDNORM | POLLERR)) {
				if ( (n = readline(sockfd, line, MAXLINE)) < 0) {
					if (errno == ECONNRESET) {
							/*4connection reset by client */
#ifdef	NOTDEF
						printf("client[%d] aborted connection\n", i);
#endif
						Close(sockfd);
						client[i].fd = -1;
					} else
						err_sys("readline error");
				} else if (n == 0) {
						/*4connection closed by client */
#ifdef	NOTDEF
					printf("client[%d] closed connection\n", i);
#endif
					Close(sockfd);
					client[i].fd = -1;
				} else
					Writen(sockfd, line, n);

				if (--nready <= 0)
					break;				/* no more readable descriptors */
			}
		}
	}
}
Ejemplo n.º 13
0
int ns_update(const char *ip_addr) {

	/* define local variables */
	int nsupdate_sockfd;
	struct hostent *nsupdate_server_ent;
	struct sockaddr_in nsupdate_servaddr;
	ssize_t n;
	struct timeval tv;
	char inbuf[MAX_RECV_LINE];
	char outbuf[MAX_RECV_LINE];
	char tmpbuf[65];
	char md5response[33];

	/* init vars */
	tv.tv_sec = NSUPDATE_TIMEOUT;
	tv.tv_usec = 0;
	bzero(inbuf, MAX_RECV_LINE);
	bzero(outbuf, MAX_RECV_LINE);
	bzero(&nsupdate_servaddr, sizeof(nsupdate_servaddr));
	nsupdate_servaddr.sin_family = AF_INET;
	nsupdate_servaddr.sin_port = htons(nsupdate_server_port);
	bzero(tmpbuf, 65);
	bzero(md5response, 33);


	/* get IP of nsupdate_server, and setup nsupdate_servaddr */
	nsupdate_server_ent = gethostbyname(nsupdate_server);
	if (nsupdate_server_ent == NULL) {
		logwrite("ns_update: Error resolving nsupdate_server");
		return(-1);
	}
	memcpy(&nsupdate_servaddr.sin_addr.s_addr, nsupdate_server_ent->h_addr_list[0], nsupdate_server_ent->h_length);

    if ((nsupdate_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		logwrite("ns_update: Error opening socket");
		return(-1);
	}

    /* set timeout */
	setsockopt(nsupdate_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    if (connect(nsupdate_sockfd,(SA *)&nsupdate_servaddr,sizeof(nsupdate_servaddr)) < 0) {
        logwrite("ns_update: Error connecting to nsupdate_server");
        close(nsupdate_sockfd);
        return(-1);
	}

	/* read the welcome message */
	if (read_server_cooked(nsupdate_sockfd, inbuf) < 0) {
        logwrite("ns_update: Error getting welcome message");
        close(nsupdate_sockfd);
        return(-1);
	}

	/* send agent identity */
	n = sprintf(outbuf, "agent %s/%s\n", PROG_NAME, VERSION);
	Writen(nsupdate_sockfd, outbuf, n);
	if (read_server_cooked(nsupdate_sockfd, inbuf) < 0) {
        logwrite("ns_update: Error after send agent identity");
        close(nsupdate_sockfd);
        return(-1);
	}


	/* send login command */
	n = sprintf(outbuf, "login %s digest-md5-text\n", login_id);
	Writen(nsupdate_sockfd, outbuf, n);
	if (read_server_cooked(nsupdate_sockfd, inbuf) < 0) {
        logwrite("ns_update: Error after send login command");
        close(nsupdate_sockfd);
        return(-1);
	}

	/* now the challange is in the inbuf, calculate the response */

	if (strlen(md5password) == 0) {
		MD5Str(password, tmpbuf);	/* gen md5 string of the password */
	} else {
		strncpy(tmpbuf, md5password, 32);
	}
	strncat(tmpbuf, inbuf, 32); /* glue md5 of password and challenge */
	MD5Str(tmpbuf, md5response);

	/* send response */
	n = sprintf(outbuf, "response %s\n", md5response);
	Writen(nsupdate_sockfd, outbuf, n);
	if (read_server_cooked(nsupdate_sockfd, inbuf) < 0) {
        logwrite("ns_update: Error after send response");
        close(nsupdate_sockfd);
        return(-1);
	}

	/* send update request */
	n = sprintf(outbuf, "a_update online %s %s\n", hostname, ip_addr);
	Writen(nsupdate_sockfd, outbuf, n);
	if (read_server_cooked(nsupdate_sockfd, inbuf) < 0) {
        logwrite("ns_update: Error after update request");
        close(nsupdate_sockfd);
        return(-1);
	}

	/* send exit command */
	n = sprintf(outbuf, "%s\n", "exit");
	Writen(nsupdate_sockfd, outbuf, n);
	read_server_cooked(nsupdate_sockfd, inbuf); /* read last message */

	return(0);
	close(nsupdate_sockfd);
}
Ejemplo n.º 14
0
int main (int argc, char **argv)
{
	//Initialize variables
    int i, j, maxindex, maxfd, listenfd, connfd, nready;
	client clients[BACKLOG];
    ssize_t	n;
    fd_set	rset, allset;
    msg	output;
	char line[READDATA];
    socklen_t clilen;
    struct sockaddr_in cliaddr, servaddr;
    int yes = 1;
    
    //get the listening fd
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);
	
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(PORT);
	printf("Server started on port %d\n", PORT);
	
    if((setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)))
       == -1) {
        perror("setsockopt");
    }
	
    //Bind the host and init listen socket
    Bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
	
    Listen(listenfd, BACKLOG);
	
    //initialize and index into array
    maxfd = listenfd;	
    maxindex = -1;		
    //set up clients
    for (i = 0; i < BACKLOG; i++) {
		clients[i].socket = -1;	
    }
    
    //clear and add listen socket to set
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);
    
    while(1) {
    	
    	//set up select, rset is a temp fd set
		rset = allset;		
		nready = Select(maxfd+1, &rset, NULL, NULL, NULL);
		
		//new client connection
		if (FD_ISSET(listenfd, &rset)) {	
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);	
			//Client is accepted
			for (i = 0; i < BACKLOG; i++) {
				if (clients[i].socket < 0) {
					clients[i].socket = connfd;	/* save descriptor */
					char name[WRITEDATA-1];
					//initialize client info
					sprintf(name, "client[%d]", i);
					strncpy(clients[i].name, name, strlen(name));
					strncpy(clients[i].status, "", BACKLOG);
					sprintf(line,"A new client has connected.\n");
					break;
				}
			}
			
			//If too many clients
			if (i == BACKLOG) {
				sprintf(line,"too many clients, try again later.\n");
			}
			
			//add new fd to set
			FD_SET(connfd, &allset);
			if (connfd > maxfd) {
				maxfd = connfd;
			}
			//Maxindex is max index of client set
			if (i > maxindex) {
				maxindex = i;	
			}
			
			//Write messages to client
			for(j=0; j<=maxindex; j++)
			{
				if(clients[j].socket>=0)
				{
					Writen(clients[j].socket, line, strlen(line));
				}
			}
			
			if (--nready <= 0)
				continue;	/* no more readable descriptors */
		}
		
		for (i = 0; i <= maxindex; i++) {	/* check all clients for data */
			//if the client has no data, go to the next one
			if ( (clients[i].socket) < 0) {
				continue;
			}
			
			//need to set a flag to see if the msg is global or not
			//and another variable to see if PM user was found
			int isglobal=0;
			int found = 0;
			
			//Check a client who is connected
			if (FD_ISSET(clients[i].socket, &rset)) {
				
	       //The client logs off if there is nothing incoming from the socket
				if ( (n = Readline(clients[i].socket, line, WRITEDATA)) <= 0) {

					sprintf(line, "%s (%s) logged off.\n", clients[i].name, 
							clients[i].status);
					Close(clients[i].socket);
					FD_CLR(clients[i].socket, &allset);
					clients[i].socket = -1;
					
			//else the client sent data, so parse it		
				} else {
					parseInput(line, &output);

					//switch depending on type of input
					switch(output.type){
					
					//Login
						case 'L': 
						{
							//Change to the new username
							char oldname[WRITEDATA-1];
							strncpy(oldname, clients[i].name, WRITEDATA-1);
							strncpy(clients[i].name, 
									output.message, WRITEDATA-1);
							
							for(j=0; j<=maxindex; j++) {
								
								//If the client id is already connected, 
								//output the error message
								if(clients[j].socket>=0 &&
								   strncmp(clients[j].name, output.message,
										   WRITEDATA-1)==0 && j != i) {
									
									Writen(clients[i].socket,
							"You are not allowed to logon again.\n", READDATA);
									
									//disconnect the client
									Close(clients[i].socket);
									FD_CLR(clients[i].socket, &allset);
									clients[i].socket = -1;
								}
							}
							
							sprintf(line, 
									"%s has logged on.\n", clients[i].name);
							break;
						}
						
						//Change of status
						case 'S':
						{
							strncpy(clients[i].status, 
									output.message, WRITEDATA);
							sprintf(line, "%s (%s):\n", clients[i].name, 
									clients[i].status);
							break;
						}
						
						//Broadcast message
						case 'B': 
						{
							sprintf(line, "%s (%s): %s\n", clients[i].name, 
									clients[i].status, output.message);
							break;
						}
						
						//PM another user
						case 'M': 
						{
						isglobal=1;
					
						//if user pm's themself
						if (strncmp(clients[i].name,output.otheruser,
								strlen(clients[i].name)) == 0) {
							sprintf(line, "You cannot PM yourself.\n");
							Writen(clients[i].socket,line,strlen(line));
							break;
						}
							
						//Check for other user and send PM
							for(j=0; j<=maxindex; j++) {
							if(clients[j].socket>=0)  {
								if(!strncmp(clients[j].name,
										output.otheruser, WRITEDATA-1)) {
									found = 1;
									sprintf(line, "%s (PM): %s\n", 
											clients[i].name, output.message);
									Writen(clients[j].socket,
											line, strlen(line));
									break;
								}
						       }
						    }

							//If user was not found
							if (found == 0) {
								sprintf(line,"User is not online.\n");
								Writen(clients[i].socket,line,strlen(line));
							}
							
							break;
							
							}
						}

					}
				
				//If the message is a global msg, then write to the client
					if(isglobal==0) {
						
						for(j=0; j<=maxindex; j++) {
							
							if(clients[j].socket>=0) {
								Writen(clients[j].socket, line, strlen(line));
							}
						}
					}
					
					if (--nready <= 0)
						break;	/* no more readable descriptors */
				}
			
		}
    }
}
Ejemplo n.º 15
0
int main(int argc, char** argv)
{
    int i, maxi, maxfd, listenfd,connfd, sockfd;
    int nready;
    ssize_t n;
    char buf[MAXLINE];
    socklen_t clilen;
    struct pollfd client[OPEN_MAX];
    struct sockaddr_in cliaddr, servaddr;

    fprintf(stdout, "main\n");
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    Bind(listenfd, (SA*) &servaddr, sizeof(servaddr));

    fprintf(stdout,"begin listen");
    Listen(listenfd, LISTENQ);
    client[0].fd = listenfd;
    client[0].events = POLLRDNORM;
    for(i = 0; i != OPEN_MAX; ++i)
    {
        client[i].fd = -1;
    }
    fprintf(stdout,"begin loop");
    maxi = 0;
    for(; ; ){
        fprintf(stdout,"begin poll");

        nready = Poll(client, maxi + 1, INFTIM);
        if(client[0].revents & POLLRDNORM){
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA*) & cliaddr, & clilen);
            fprintf(stdout,"accept success");

            for(i = 1; i != OPEN_MAX; ++i)
            {
                if(client[i].fd < 0)
                {
                    client[i].fd = connfd;
                    break;
                }
            }
            if(i == OPEN_MAX)
                err_quit("too many clients");
            client[i].events = POLLRDNORM;
            if(i > maxi)
                maxi = i;
            if(--nready <= 0)
                continue;
        }
        for(i = 1; i <= maxi; ++i){

            if( (sockfd = client[i].fd) <0)
                continue;
            if(client[i].revents & (POLLRDNORM | POLLERR)){
                if((n = read(sockfd, buf, MAXLINE)) < 0){
                    if(errno == ECONNRESET){
                        Close(sockfd);
                        client[i].fd = -1;
                    }
                    else
                    {
                        err_sys("read error");
                    }
                }else if(n == 0)
                {
                    Close(sockfd);
                    client[i].fd =-1;
                }
                else{
                    Writen(sockfd, buf, n);
                }
               if(--nready <=0)break;
            }
        }
    }
}
Ejemplo n.º 16
0
static int
test_icapstartlines(const char **slines){
	struct sockaddr_in sina;
	const char **cur;
	int ret = -1,sd;

	if(common_start()){
		goto done;
	}
	memset(&sina,0,sizeof(sina));
	sina.sin_port = htons(ICAP_DEFAULT_PORT);
	sina.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	sina.sin_family = AF_INET;
	for(cur = slines ; *cur ; ++cur){
		if((sd = make_tcp_socket(PF_INET)) >= 0){
			if(Connect(sd,(struct sockaddr *)&sina,sizeof(sina)) == 0){
				printf(" Sending %s",*cur);
				if((strlen(*cur) == 0 || Writen(sd,*cur,strlen(*cur)) == 0) /*&& Writen(sd,CRLF,__builtin_strlen(CRLF)) == 0*/){
					if(Shutdown(sd,SHUT_WR) == 0){
						int i,v = 0;
						char c;

						while((i = read(sd,&c,sizeof(c))) == sizeof(c)){
							if(!v){
								printf("  ");
								v = 1;
							}
							putc(c,stdout);
							if(c == '\n'){
								v = 0;
							}
						}
						if(i == 0){
							if(Close(sd)){
								goto done;
							}
							continue; // mmm, spaghetti
						}else{
							if(i < 0){
								moan("Couldn't read reply on %d\n",sd);
							}else{
								bitch("Got %d reading on %d\n",i,sd);
							}
						}
					}
				}
			}
			Close(sd);
		}
		goto done;
	}
	ret = 0;

done:
	ret |= close_icap_servers();
	ret |= reap_poller_thread(snarepoller);
	ret |= destroy_poller(snarepoller);
	ret |= stop_config();
	ret |= stop_fileconf();
	return ret;
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
  char string_remote_ip_address[100];
  char string_local_ip_address[100];
  short int remote_port_number;
  int socketfd[2], ris;
  int n, nread, nwrite;
  char buflettura[2][LENVETLETTURA];
  char bufscrittura[2][LENVETSCRITTURA];
  unsigned int sumlettura[2];
  unsigned int sum[2];
  int K,H;

  if	( (sizeof(int)!=sizeof(long int)) ||  (sizeof(int)!=4)  )
  {
	printf ("dimensione di int e/o long int != 4  -> TERMINO\n");
	fflush(stdout);
    	exit(1);
  }

  if((argc!=3)&&(argc!=4)) { printf ("necessari 2 o 3 parametri\n"); usage(); exit(1);  }
  else {
	strncpy(string_remote_ip_address, argv[1], 99);
	remote_port_number = atoi(argv[2]);
	if(argc==4)
		strncpy(string_local_ip_address, argv[3], 99);
  }
  
  if( ! Init_TCP_Session_Module(NULL) )
  {
	printf ("Init_TCP_Session_Module() failed\n");
	fflush(stdout);
	exit(1);
  }

  ris= TCPS_setup_connection(&(socketfd[0]), string_remote_ip_address, remote_port_number);
  if (!ris)  {
	printf ("impossibile connettersi al server %s %d\nTERMINO!!\n", 
			string_remote_ip_address, remote_port_number );
	fflush(stdout);
	return(0);
  }
  printf ("dopo prima Connect()\n");
  fflush(stdout);

  ris= TCPS_setup_connection(&(socketfd[1]), string_remote_ip_address, remote_port_number);
  if (!ris)  {
	printf ("impossibile connettersi al server %s %d\nTERMINO!!\n", 
			string_remote_ip_address, remote_port_number+1 );
	fflush(stdout);
	return(0);
  }
  printf ("dopo seconda Connect()\n");
  fflush(stdout);


  for(K=1;K>=0;K--)
  {
  	nread=sizeof(int);
  	printf ("Readn() sum \n");
  	fflush (stdout);
  	n = Readn (socketfd[K], (char*) &(sum[K]), nread);
  	if (n != nread)
	{	
		printf ("Readn() sum failed \n");
		fflush(stdout);
		return (0);
	}
	sum[K]=ntohl(sum[K]);
	printf("connessione %d ricevuto valore somma %u\n", K, sum[K] );
	fflush(stdout);
  }

  for(K=1;K>=0;K--)
  {
	/* scrittura */
	nwrite = LENVETSCRITTURA;
	printf ("Writen()\n");
	fflush (stdout);
	n = Writen (socketfd[K], bufscrittura[K], nwrite );
	if (n != nwrite)
	{
		printf ("Writen() failed \n");
		fflush(stdout);
		return (0);
	}

	/* lettura */
  	for(H=0;H<10;H++)
  	{
		nread=LENVETLETTURA/10;
		/* nread=LENVETLETTURA;*/
		printf ("Readn()\n");
		fflush (stdout);
		n = Readn (socketfd[K], ((char*)(buflettura[K]))+(H*nread), nread);
		/* n = Readn (socketfd[K], buflettura[K], nread);*/
		if (n != nread)
		{
			printf ("Readn() failed \n");
			fflush(stdout);
	    		return (0);
		}
	}
  	sumlettura[K]=sommavet(buflettura[K],LENVETLETTURA);
	printf("connessione %d somma ricevuta %u somma calcolata %u\n", K, sum[K], sumlettura[K] );
	/*
	stampavet(buflettura[K],LENVETLETTURA);
	fflush(stdout);
	*/
	if(sumlettura[K]!=sum[K])
	{
		printf ("\033[33;35;1m somma errata: errore in trasmissione dati\n \033[0m ");
		fflush(stdout);
	    	return (0);
	}
  }	

  /* chiusura */
  for(K=0;K<2;K++)
	Close(socketfd[K]);

  if( ! Close_TCP_Session_Module(NULL) )
  {
	printf ("\033[33;35;1m Close_TCP_Session_Module() failed\n \033[0m ");
	fflush(stdout);
	exit(1);
  }

  printf ("TUTTO OK\n");
  return(0);
}
Ejemplo n.º 18
0
int main(int argc, char ** argv){
	int  i, maxi, maxfd, listenfd, connfd, sockfd,val,nwritten;
	int  nready, client[NUMBEROFSTATIONS];
	ssize_t  n;
	fd_set   rset, allrset, wset,allwset;
	socklen_t    clilen;
	struct sockaddr_in    cliaddr, servaddr;
	int frame_number;
	int source_station_number;
	int destination_sockfd; //used to assign destination station socket number, 
	char *message1; //used to store first message
	char *message2; //used to store second message
	char source[INET_ADDRSTRLEN]; //used to the  third parameter of function inet_ntop
	char *sourceIP; //used to stored IP address of SP
	
	/* dest is an array that will store the destination station numbers
	and their corresponding socket descriptors. This will later be used to 
	send frame to destination station after receiving both messages of frame */	
	char *destinationIP; 
	char *destination_addr;
	int stored_destination_number;
	struct destination dest[NUMBEROFSTATIONS];
	/* initilize each station's sockfd to -1 */
	for (i = 0; i < NUMBEROFSTATIONS; i++){
		(dest + i)->destination_sockfd = -1;
	}
	
	struct frame * receiving_framePtr;
	struct cbp_storage  cbs;
	char col_mes[COLLISIONMESSAGE] = "Collision";
	char *collision_message = col_mes;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	maxfd = listenfd;                       /* initialize */
	maxi = -1;                                      /* index into client[] array */
	
	/* Set to non-blocking mode using Fcntl for non-blocking IO*/
	
	/* Set socket descriptor that write to CBP output */
	val = Fcntl(fileno(stdout), F_GETFL, 0);
	Fcntl(fileno(stdout), F_SETFL, val | O_NONBLOCK);
	
	val = Fcntl(fileno(stdin), F_GETFL, 0);
	Fcntl(fileno(stdin), F_SETFL, val | O_NONBLOCK);
	for (i = 0; i < NUMBEROFSTATIONS; i++)
			client[i] = -1;                 /* -1 indicates available entry */
	FD_ZERO(&allrset);
	FD_ZERO(&allwset);
	FD_SET(listenfd, &allrset);
	
	maxfd = listenfd;
	
	int ctClient = 0;
	


    for ( ;; ) {
			
	rset = allrset; 
	//wset = allwset;/* structure assignment */
	nready = Select(maxfd+1, &rset, NULL, NULL, NULL);
	if (ctClient == NUMBEROFSTATIONS){			
		if (FD_ISSET(listenfd, &rset)) {        /* new client connection */
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
			
			printf("New connection, sockfd: %d\n",connfd);	
			/* Save the just-connected station, e.i. its socket descriptor and its station number
			This information will later be used to send frame to destination station after
			receiving both message of frame */
			destinationIP = Inet_ntop(AF_INET, &cliaddr.sin_addr,source,INET_ADDRSTRLEN);
			stored_destination_number = ston(destinationIP);
			for (i = 0; i < NUMBEROFSTATIONS; i++){
				if((dest+i)->destination_sockfd < 0){
					(dest+i)->destination_sockfd = connfd;
					(dest+i)->destination_station_number = stored_destination_number;
					break;
				}
			}			
			/* Set socket descriptor to and from SP using Fcntl for non-blocking IO*/	
			val = Fcntl(connfd, F_GETFL, 0);
			Fcntl(connfd, F_SETFL, val | O_NONBLOCK);

			for (i = 0; i < NUMBEROFSTATIONS; i++)
				if (client[i] < 0) {
					client[i] = connfd; 
					ctClient++; 
					break;
				}
			FD_SET(connfd, &allrset);
			FD_SET(connfd, &allwset);

			if (connfd > maxfd)	
					maxfd = connfd;                
			if (i > maxi)
					maxi = i;                           

			if (--nready <= 0)
					continue;                          
	
		}       
		else //Clients full
		{
			break;
		}
	}
	}
	
	/*All Sps are now connect to the CBP, ready for sending frames*/	
	
	/*buffer_acquired is set to:   0 when first part of frame received																       1 when the second part of the frame sent, making the buffer ready for new frame 
					 or when a collision happens, discards the remaining part of the frame, allows stations to acquire the CBP storage
	*/
	char response;	
	printf("All stations are connected, ready to exchage data (Y/N):  \n");
        scanf("%*c %c",&response);
        if( (response == 'y') || (response == 'Y') ){	
	int buffer_acquired = 1;
	for( ; ; ){
	
		
		nready = Select(maxfd+1, &rset, &wset, NULL, NULL);

        for (i = 0; i <= maxi; i++) {   /* check all clients for data */
			sockfd = client[i];
			FD_SET(sockfd, &rset);
			sourceIP = Inet_ntop(AF_INET, &cliaddr.sin_addr,source,INET_ADDRSTRLEN);
			source_station_number = ston(sourceIP);
			
			if(buffer_acquired){	
				if(FD_ISSET(sockfd, &rset)){
					buffer_acquired = 0;
					if(n = Read(sockfd, receiving_framePtr,MAXLINE) == 0){
							Close(sockfd);
							FD_CLR(sockfd,&allrset);
							client[i] = -1;
					}
					else{
						/* Get information from struct frame type variable pointed by receiving_framePtr pointer
						that is received from SP */
						frame_number = receiving_framePtr->frame_number;						
						message1 = receiving_framePtr->message1;
						destination_addr = receiving_framePtr->destination_addr;
						int destination_station_number = ston(destination_addr);
						
						//inspect the message1					
						cbs.source_station_sd = sockfd;
						cbs.source_station_number = source_station_number;
						cbs.destination_station_number = destination_station_number;
						cbs.frame_number = frame_number;			
						strcpy(cbs.message1,message1);

						/*Turn on the bit to write to stdout*/
						FD_SET(fileno(stdout), &wset);
						if(FD_ISSET(fileno(stdout), &wset))
							fprintf(stdout,"Receive %s of frame %d from Station %d,to Station %d\n",
											message1,frame_number,source_station_number,destination_station_number);														
					}
					if (--nready <= 0)
						break;				/* no more readable descriptors */
				}
			}
			else{ 
				/* Buffer already store first message of a frame of a station
				Check if the receiving message is the second frame of that frame or
				the first message of a frame from another station */
				if (FD_ISSET(sockfd, &rset)){
					if(n = Read(sockfd, receiving_framePtr,MAXLINE) == 0){
						Close(sockfd);
						FD_CLR(sockfd,&allrset);
						client[i] = -1;
					}				
					else{/* Inspect the message if it is the second message 
							or the first message from another frame of another station*/
	
						/* Get information from struct frame type variable pointed by receiving_framePtr pointer
						that is received from SP */
						frame_number = receiving_framePtr->frame_number;			//get frame number				
						message2 = receiving_framePtr->message2;						//get the second message
						destination_addr = receiving_framePtr->destination_addr;	//get the destination address (string)
						int destination_station_number = ston(destination_addr);	//convert to number using ston function

						//Inspect the message
						//Check if the current source station number is the one whose first message has already been saved to CBP storage
						//If yes, save the second message
						if(cbs.source_station_number == source_station_number && 
									cbs.frame_number == frame_number){
							if(strcmp(message2,"part 2"==0)){
								strcpy(cbs.message2,message2);
							/*Turn on the bit to write to stdout*/
							FD_SET(fileno(stdout), &wset);
							if(FD_ISSET(fileno(stdout), &wset))
								fprintf(stdout,"Receive %s of frame %d from Station %d,to Station %d\n",
												message1,frame_number,source_station_number,destination_station_number);
								/* Turn on the bit in the wset to write to desination station the first message 
									Get the destination socket number from the dest array
								*/
								
								for( i = 0; i<NUMBEROFSTATIONS; i++){
									if((dest+i)->destination_station_number == cbs.destination_station_number)
										break;
								}
								destination_sockfd = (dest+i)->destination_sockfd;
								FD_SET(destination_sockfd, &wset);
							}
						}
						else{ /* Receiving frame from another station, inform both station a collision*/
						
							 /* Sending collision message to station that accquired the bus, discards the remaing parts of frame */						 
							buffer_acquired = 1;
							FD_SET(cbs.source_station_sd, &wset);		
							if(FD_ISSET(cbs.source_station_sd, &wset))
								Writen(cbs.source_station_sd, collision_message, strlen(COLLISIONMESSAGE));
								
							/*Sending collision message to another station*/
							if(FD_ISSET(sockfd, &wset))
								Writen(sockfd, collision_message, strlen(COLLISIONMESSAGE));
						}
					}
					if (--nready <= 0)
						break;				/* no more readable descriptors */
				}	
			}
			/* Sending the first message of the frame to destinaition SP*/

				
			} 
					

        }

    }




}
Ejemplo n.º 19
0
int
main(int argc, char **argv)
{
    int                 i,j, maxi, maxfd, listenfd, connfd, sockfd;
    int                 nready, client[FD_SETSIZE];
    ssize_t             n;
    fd_set              rset, allset;
    char                buf[MAXLINE];
    socklen_t           clilen;
    struct sockaddr_in  cliaddr, servaddr;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(7746);

    Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

    Listen(listenfd, LISTENQ);

    maxfd = listenfd;           /* initialize */
    maxi = -1;                  /* index into client[] array */
    for (i = 0; i < FD_SETSIZE; i++)
        client[i] = -1;         /* -1 indicates available entry */
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);
/* end fig01 */

/* include fig02 */
    for ( ; ; ) {
        rset = allset;      /* structure assignment */
        nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

        if (FD_ISSET(listenfd, &rset)) {    /* new client connection */
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef  NOTDEF
            printf("new client: %s, port %d\n",
                    Inet_ntop(AF_INET, &cliaddr.sin_addr, 4, NULL),
                    ntohs(cliaddr.sin_port));
#endif

            for (i = 0; i < FD_SETSIZE; i++)
                if (client[i] < 0) {
                    client[i] = connfd; /* save descriptor */
                    break;
                }
            if (i == FD_SETSIZE)
                err_quit("too many clients");

            FD_SET(connfd, &allset);    /* add new descriptor to set */
            if (connfd > maxfd)
                maxfd = connfd;         /* for select */
            if (i > maxi)
                maxi = i;               /* max index in client[] array */

            if (--nready <= 0)
                continue;               /* no more readable descriptors */
        }

        for (i = 0; i <= maxi; i++) {   /* check all clients for data */
            if ( (sockfd = client[i]) < 0)
                continue;
            if (FD_ISSET(sockfd, &rset)) {
                if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
                        /*4connection closed by client */
                    Close(sockfd);
                    FD_CLR(sockfd, &allset);
                    client[i] = -1;
                } else
                    for(j = 0; j<= maxi;j++) {
                        if ((sockfd = client[j]) > 0 && i != j && strlen(buf) > 0) { //像自己以外的客户端发送信息
                            Writen(sockfd, buf, n);
                        }
                    }

                    Writen(fileno(stdout), buf, n);

                if (--nready <= 0)
                    break;              /* no more readable descriptors */
            }
        }
    }
}
Ejemplo n.º 20
0
/* getnrd 
   
   write command to wthd and read response
   IPv4 version
 
*/
int getnrd(unsigned char *data, int *mdat, struct cmd *pcmd) {
    int                  sockfd, n, len;
    char                 sendline[MAXLINE] = "1";
    struct sockaddr_in   servaddr;

    struct in_addr **pptr, *addrs[2];
    struct hostent *hp;
    struct servent *sp;
	
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;

    /* hostname or ipaddress */
    if (inet_pton(AF_INET, pcmd->hostname, &servaddr.sin_addr) == 1) {
	  addrs[0] = &servaddr.sin_addr;
	  addrs[1] = NULL;
	  pptr = &addrs[0];
    } else if ( (hp = gethostbyname(pcmd->hostname)) != NULL) {
	  pptr = (struct in_addr **) hp->h_addr_list;
    } else {
	  werrno = h_errno;
	  syslog(LOG_INFO,"hostname error for %s: %s", 
		 pcmd->hostname, hstrerror(h_errno));
	  return (-1);
	  }
    /* port number or service name */
    if ( (n = atoi(pcmd->port)) > 0)
	  servaddr.sin_port = htons(n);
    else if ( (sp = getservbyname(pcmd->port, "tcp")) != NULL)
	  servaddr.sin_port = sp->s_port;
    else {
	  syslog(LOG_INFO,"getservbyname error for %s", pcmd->port);
	  werrno = ENET;
	  return(-1);
    }
    /* connect to server */
    for ( ; *pptr != NULL; pptr++) {
      if ( ( sockfd = Socket(AF_INET, SOCK_STREAM, 0)) == -1 )
	return(-1);

      memmove(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
      Sock_ntop((SA *) &servaddr, sizeof(servaddr));
	  
      if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == 0)
	break; /* success */

      werrno = errno;
      syslog(LOG_INFO, "getnrd: connect error: %s",
	     strerror(werrno));
      return(-1);

      close(sockfd);
    }
    if (*pptr == NULL ) {
      syslog(LOG_INFO, "unable to connect");
      werrno = ENET;
      return(-1);
    }

    /* write command to server */
    snprintf(sendline, sizeof(sendline), "%d\r\n", (*pcmd).command);
    if ( Writen(sockfd, sendline, 1) == -1 )
      return(-1);
    
    /* read response. rwstephens unp p.10 */
    while ( ( n = read(sockfd, data, MAXBUFF)) > 0) {
      data[n] = 0;
    }

    /* code doesn't work. why?
       if (Readline(sockfd, line, MAXLINE) == 0)
       err_quit("getnrd: server terminated prematurely");
    */

    len = wstrlen(data);
    *mdat = len;
	
    return(0);
}
int main(int argc, char **argv)
{
    int sockfd, listenfd, connfd, maxfd;
    int nready, n, i, maxi, client[FD_SETSIZE];
    socklen_t clilen;
    struct sockaddr_in cliaddr, servaddr;
    fd_set rset, allset;
    char buf[MAXLINE];


    listenfd = Socket(AF_INET, SOCK_STREAM, 0);
    bzero(&servaddr, sizeof servaddr);
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT); /* well-known port defined in unp.h == 9877 */

    Bind(listenfd, (SA *) &servaddr, sizeof servaddr);
    Listen(listenfd, LISTENQ);

    maxfd = listenfd;
    maxi = -1;
    for (i = 0; i < FD_SETSIZE; i++)
        client[i] = -1;
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);

    for (;;) {
        rset = allset;
        nready = Select(maxfd+1, &rset, NULL, NULL, NULL);
        if (FD_ISSET(listenfd, &rset)) {
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
            for (i = 0; i < FD_SETSIZE; i++)
                if (client[i] == -1) {
                    client[i] = connfd;
                    break;
                }

            if (i == FD_SETSIZE)
                err_quit("too many clients");

            FD_SET(connfd, &allset);
            if (connfd > maxfd)
                maxfd = connfd;
            if (i > maxi)
                maxi = i;
            if (--nready <= 0)
                continue;
        }

        for (i = 0; i <= maxi; i++) {
            if ((sockfd = client[i]) < 0)
                continue;
            if (FD_ISSET(sockfd, &rset)) {
                if ((n = Read(sockfd, buf, MAXLINE)) == 0) {
                    Close(sockfd);
                    FD_CLR(sockfd, &allset);
                    client[i] = -1;
                } else
                    Writen(sockfd, buf, n);
                if (--nready <= 0)
                    break;
            }
        }
    }
    exit(0);
}
Ejemplo n.º 22
0
int main(int argc, char * argv[])
{

	//init variables
    int sockfd;
    char buf[READDATA];
    struct hostent *hp;
    struct sockaddr_in peer;
	fd_set master;
    peer.sin_family = AF_INET;
    peer.sin_port = htons(PORT);

    
    if ( argc != 2 )
    {  
		fprintf(stderr, "Usage: %s hostname\n", argv[0]);
		exit(1);
    }
	
    /* fill in peer address */
    hp = gethostbyname(argv[1]);                
    if ( hp == NULL ) {  
		fprintf(stderr, "%s: %s unknown host\n",
				argv[0], argv[1]);
		exit(1);
    }
	
    peer.sin_addr = *((struct in_addr *)hp->h_addr);
	
    /* create socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    /* request connection to sockfd */
    if (connect(sockfd, (struct sockaddr *)&peer, sizeof(peer)) == -1)
    {  
		perror("client:connect"); close(sockfd);
		exit(1); 
    }
    
    //clear it and add stdin and server to the set
	FD_ZERO(&master);  
	FD_SET(STDIN_FILENO, &master); 
	FD_SET(sockfd, &master);
	//Make a temp set
	fd_set fds;
	
	//Print welcome message
    printf("Welcome, please login first by typing L followed by your id. \n"
    		"You can update your status by typing S followed by"
    		" a message.\n You can broadcast a message by typing B followed by"
    		 " a message.\n You can PM another user by typing M followed by a"
    		" user name, and then the message.\n");

	while(1) {
		//fds gets reset
		fds = master; 
		
		//Use select to check for input from stdin and server
		Select(sockfd+1, &fds ,NULL,NULL,NULL); 
		if(FD_ISSET(STDIN_FILENO, &fds)) { 
			
			//Read from stdin
			fgets(buf, WRITEDATA, stdin);
			
			//Error checking
			//check for invalid input
		    if (buf == NULL || buf[1] != ' ') {
		    	fprintf(stderr, "Invalid command\n");
		    	continue;
		    } else if (buf[0] != 'L' && buf[0] != 'M' && buf[0] != 'B'
		    	&& buf[0] != 'S') {
		    	fprintf(stderr, "Invalid command\n");
		    	continue;
		    } 
		    
		    //Send to server
			if (strlen(buf) > 0) {
			Writen(sockfd, buf, strlen(buf)); 
			}
		} 
		//If server has outputted data
		else if(FD_ISSET(sockfd, &fds)) {
				//Print what the server sent out
				if ( (Readline(sockfd, buf, READDATA)) <= 0) {
					Close(sockfd);
					printf("Server closed\n");
					exit(0);
				}
				printf("%s", buf);
				
			} 
	} 
}
Ejemplo n.º 23
0
int main(int argc, char *argv[]) {


  int sockfd;
  int len;

  struct sockaddr_in addr;
  int result;

  char buf[BUFSIZE];
  char buf1[BUFSIZE];
  struct hostent *host;

  if (argc < 2) {
    fprintf(stderr, "Usage : echocli hostname\n");
    exit(EXIT_FAILURE);
  }


  /* get name of server from command-line argumet */
  host = gethostbyname(argv[1]);
  if (!host) {
    fprintf(stderr, "Unable to connect to host %s\n", argv[1]);
    exit(EXIT_FAILURE);
  }

  /* make sure address is IP address */
  if (host->h_addrtype != AF_INET) {
    fprintf(stderr, "%s : not an IP host", argv[1]);
    exit(EXIT_FAILURE);
  }
  

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  
  addr.sin_family = AF_INET;

  /* get the first address, cast it to the appropriate pointer and then dereference it */
  addr.sin_addr = *(struct in_addr *) *host->h_addr_list;

  addr.sin_port = htons(PORTNO);
  //addr.sin_port = PORTNO;

  len = sizeof(addr);

  result = connect(sockfd, (struct sockaddr *) &addr, len);


  if (result < 0) {
    perror("error : client\n");
    exit(1);
  }
  else
    fprintf(stdout, "Established connection to server ...\n");



  /* read data from standard input on client */
  int n = read(STDIN_FILENO, buf, BUFSIZE);

  buf[n] = '\0';

  Writen(sockfd, buf, n);
  /* read server message */
  Readline(sockfd, buf1, BUFSIZE);

  fprintf(stdout, "msg from server = %s\n", buf1);

  close(sockfd);

  return 0;
  
}
Ejemplo n.º 24
0
int
main(int argc, char **argv)
{
        Signal( SIGINT, sigInt);
	int			i, maxi, maxfd, listenfd, connfd, sockfd;
	int			nready, client[FD_SETSIZE];
	ssize_t			n;
	fd_set			rset, allset;
	char			buf[MAXLINE];
	socklen_t		clilen;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

        /* SO_REUSEADDR allows a new server to be started
         * on the same port as an existing server that is
         * bound to the wildcard address, as long as each
         * instance binds a different local IP address.
         * This is common for a site hosting multiple HTTP
         * servers using the IP alias technique */
        int reuseaddr_on = 1;
        if( setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR,
                &reuseaddr_on, sizeof( reuseaddr_on)) < 0)
        {
            // log
        }

	Bind( listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen( listenfd, LISTENQ);

	maxfd = listenfd;			/* initialize */
	maxi = -1;				/* index into client[] array */
	for ( i = 0; i < FD_SETSIZE; ++i)
		client[i] = -1;			/* -1 indicates available entry */
	FD_ZERO( &allset);
	FD_SET( listenfd, &allset);

	for ( ; ; ) {
		rset = allset;                  /* structure assignment */
                
                /* select waits for something to happen: either the establishment
                 * of a new client connection or the arrival of data, a FIN,
                 * or an RST on an existing connection */
		nready = Select( maxfd + 1, &rset, NULL, NULL, NULL);

		if ( FD_ISSET( listenfd, &rset)) {	/* new client connection */
                    
                    /* simulate busy server */
                    printf( "listening socket readable -> sleep(5)\n");
                    sleep(5);

                    /* If the listening socket is readable, a new connection has been 
                     * established. We call accept and update our data structures
                     * accordingly. We use the first unused entry in the client array
                     * to record the connected socket. The number of ready descriptors
                     * is decremented, and if it is 0, we can avoid the next for loop.
                     * This lets us use the return value from select to avoid checking
                     * descriptors that are not ready.*/
			clilen = sizeof( cliaddr);
                        printf( "accept called\n"); fflush( stdout);
			connfd = accept( listenfd, ( SA *) &cliaddr, &clilen);
                        printf( "accept returned, connfd=%d\n", connfd); fflush( stdout);

			for ( i = 0; i < FD_SETSIZE; ++i)
				if (client[i] < 0) {
					client[i] = connfd;	/* save descriptor */
					break;
				}
			if ( i == FD_SETSIZE)
				err_quit( "too many clients");

			FD_SET( connfd, &allset);	/* add new descriptor to set */
			if ( connfd > maxfd)
				maxfd = connfd;		/* for select */
			if ( i > maxi)
				maxi = i;		/* max index in client[] array */

			if ( --nready <= 0)
				continue;		/* no more readable descriptors */
		}

		for ( i = 0; i <= maxi; ++i) {	/* check all clients for data */
                    
                    /* A test is made for each existing client connection as to whether
                     * or not its descriptor is in the descriptor set returned by select.
                     * If so, a line is read from the client and echoed back to the client.
                     * If the client closes the connection, read returns 0 and we update
                     * our data structures accordingly. We never decrement the value
                     * of maxi, but we could check for this possibility each time a client
                     * closes its connection.*/
			if ( ( sockfd = client[i]) < 0)
				continue;
			if ( FD_ISSET( sockfd, &rset)) {
				if ( ( n = Read( sockfd, buf, MAXLINE)) == 0) {
					/* connection closed by client */
					Close( sockfd);
					FD_CLR( sockfd, &allset);
					client[i] = -1;
				} else
					Writen( sockfd, buf, n); /* echo */

				if ( --nready <= 0)
					break;		/* no more readable descriptors */
			}
		}
	}

    return 0;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
  int i, maxi, maxfd, listenfd, connfd, sockfd;
  int nready;
  struct pollfd client[OPEN_MAX];
  ssize_t n;
  fd_set rset, allset;
  char buf[MAXLINE];
  char inetaddrbuf[INET_ADDRSTRLEN];
  socklen_t clilen;
  struct sockaddr_in cliaddr, servaddr;

  listenfd = Socket(AF_INET, SOCK_STREAM, 0);

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);

  Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
  Listen(listenfd, LISTENQ);
  
  client[LISTEN_SOCK_IDX].fd = listenfd;
  client[LISTEN_SOCK_IDX].events = POLLRDNORM;
  for (i = 1; i< OPEN_MAX; ++i)
    client[i].fd = -1;
  maxi = 0;			/* Max index */

  for ( ; ; ) {
    nready = Poll(client, maxi+1, INFTIM); /* BLock until a new event happens */

    if (client[LISTEN_SOCK_IDX].revents & POLLRDNORM) {
      clilen = sizeof(cliaddr);
      connfd = Accept(listenfd, (SA *)&cliaddr, &clilen);
      
      inet_ntop(AF_INET, (void *)&(cliaddr.sin_addr.s_addr), inetaddrbuf, clilen);
      printf("Accepted new client from: %s:%d\n", inetaddrbuf, ntohs(cliaddr.sin_port));
      
      /* Put the new client into the clients array. */
      for (i = 1; i< OPEN_MAX; i++)
	if (client[i].fd < 0) {
	  client[i].fd = connfd;
	  break;
	}
      if (i == OPEN_MAX)
	err_quit("too many clients");
      client[i].events = POLLRDNORM;
      if(i > maxi)
	maxi = i;

      if (--nready <= 0)
	continue;
    }

    for (i = 0; i<= maxi; i++) {
      if ( (sockfd = client[i].fd) < 0)
	continue;
      if (client[i].revents & (POLLRDNORM | POLLERR) ) {
	if ( (n = read(sockfd, buf, MAXLINE)) == 0) {
	  if (errno == ECONNRESET) { /* Connection reset by client */
	    Close(sockfd);
	    client[i].fd = -1;
	  }
	} else if (n == 0) {	/* Connection closed by client */
	  Close(sockfd);
	  client[i].fd = -1;
	} else
	  Writen(sockfd, buf, n);
	if(--nready <= 0)
	  break;
      }
    }
  }
}
Ejemplo n.º 26
0
int
main(int argc, char **argv)
{
  struct pollfd clients[CLI_OPENMAX];
  long num_transmitted[CLI_OPENMAX],
    num_recieved[CLI_OPENMAX];
  struct sockaddr_in serv_addr;
  socklen_t serv_addr_len;
  int i, j, nready, tmp_fd, n;
  char buf[MAXLINE];
  size_t num_bytes, trans_size, num_open_clients;

  if (argc != 3) {
    err_quit("Usage: %s <ip_addr> <num_bytes>", argv[0]);
  }

  num_bytes = atoi(argv[2]);
  Inet_pton(AF_INET, argv[1], &serv_addr.sin_addr.s_addr);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(SERV_PORT);
  
  for (i = 0; i<CLI_OPENMAX; ++i) {
    tmp_fd = Socket(AF_INET, SOCK_STREAM, 0);
    if (connect(tmp_fd, (SA *)&serv_addr, sizeof(serv_addr)) != 0) {
      err_sys("%s: error connecting client #%d to server %s.",
	      argv[0], i, argv[1]);
    }
    clients[i].fd = tmp_fd;
    clients[i].events = POLLOUT | POLLRDNORM;
    num_transmitted[i] = 0;
    num_recieved[i] = 0;
    num_open_clients++;
  }

  while(num_open_clients > 0) {

    /*
     * Poll looks at all the structures in the array
     * and polls them for the events we've specified,
     * which in this case are POLLOUT and POLLRDNORM.
     * We ask it to block indefinitely until one of these
     * things has an event.
     */ 
    nready = Poll(clients, num_open_clients, INFTIM);
    
    for (i=0; i < CLI_OPENMAX; ++i) {
      /*
       * Now we've gotten a poll event. But we don't know 
       * who on. So we go over each and every client,
       * examining the revents (result events) structure
       * for the events we want. 
       */
      if(clients[i].fd == -1) {
	continue;
      }
      
      if(clients[i].revents & POLLOUT) {

	trans_size = rand()%MAXLINE;
	randomize_charbuf(buf, trans_size);
	Writen(clients[i].fd, buf, trans_size);

	num_transmitted[i] += trans_size;
	if(num_transmitted[i] >= num_bytes) {
	  /*
	   * When we've finished blasting out data,
	   * close down the write half of the connection.
	   * Only close the actual file descriptor once
	   * we have recieved all data from the server.
	   *
	   * When you don't do this, i.e. do a 
	   * close(clients[i].fd) immediately,
	   * you shutdown both sides and some
	   * data can get thrown away, especially
	   * w/ a large RTT or slow server.
	   * large amount of data out and get acks
	   * from the server's kernel, but eh server
	   * process has to do some special thing,
	   * and spends a while doing it. But we've
	   * sent all the data so we close, for example.
	   * The user, however, might still expect
	   * something. 
	   */
	  Shutdown(clients[i].fd, SHUT_WR);
	}
      } else if (clients[i].revents & (POLLRDNORM | POLLERR) ) {
	/* We know it won't be more than maxline, that's 
	 * how much we send (at most).
	 * 
	 * POLLERR you can't listen for, but it shows up
	 * anyway on an fd. This in our case means
	 * a RST. 
	 */
	if ( (n = read(clients[i].fd, buf, MAXLINE) == 0)) {
	  /*
	   * The server can reset the connection if,
	   * for example, the server process crashes.
	   * It could have nothing operating on that port
	   * or, a new process could be running that 
	   * isn't expecting our packets. In this case,
	   * we get an RST, which comes up to us as
	   * a bad read w/ errno = ECONNRESET.
	   */
	  if (errno == ECONNRESET) {
	    finish_client(clients[i]);
	    printf("Reset for client #%d\n", i);
	  }
	} else if (n == 0) {
	  finish_client(clients[i]);
	} else {
	  num_recieved[i] += n;
	}
      }
    }
  }
  return 0;
}
Ejemplo n.º 27
0
/* Synchronize the directory given by 'directory' with the server
 * connected at the socket 'soc'. Send a file if it is more recent on the
 * client. Retrieve a file if it is more recent on the server. Retrieve any
 * new file on the server which does not already exist in the directory.
 * Sleep execution for a predefined time and repeat the same as above.
 * @Param: directroy the directory to synchronize.
 * @Param: soc the socket at which the server is connected.
 * @Return: void.
 */
void sync_files(char *directory, int soc){

	DIR *dir;
	struct dirent *file;
	struct stat st;
	char fullpath[CHUNKSIZE];
	struct sync_message sync_packet;
	struct sync_message server_sync_packet;
	int packet_size = sizeof(sync_packet);
	int file_count, n;
	
	while(1){

		file_count = 0; //Number of files in the directory.

		if((dir = opendir(directory)) == NULL){
			perror("Opening directory: ");
			exit(1);
		}

		while(((file = readdir(dir)) != NULL) && file_count < MAXFILES){

				//Grab the full path to the file.
				strncpy(fullpath, directory, CHUNKSIZE);
				strcat(fullpath, "/");
				strncat(fullpath, file->d_name, CHUNKSIZE-strlen(fullpath));

				if(stat(fullpath, &st) != 0){
					perror("stat");
					exit(1);
				}

				//Check if this file is a regular file (ignores dot files/subdirectories).
				if(S_ISREG(st.st_mode)){
				
					//Prepare the respective sync packet to be sent.
					strncpy(sync_packet.filename, file->d_name, MAXNAME);
					sync_packet.mtime = (long int)st.st_mtime;
					sync_packet.size = (int)st.st_size;
		
					//Write the sync packet to the server.			
					Writen(soc, &sync_packet, packet_size);
		
					//Read the server's resposne to the sent sync packet.
					if((n = Readn(soc, &server_sync_packet, packet_size)) != packet_size){
						fprintf(stderr, "Communitation mismatch: Server did not acknowledge sync packet.\n");
						Close(soc);
						exit(1);
					}

					//Determine if this file has to be sycned either way.
					if(server_sync_packet.mtime < sync_packet.mtime){ //Client has a newer version.
						printf("TX: Sending file: %s\n", file->d_name);
						send_file(soc, directory, sync_packet.filename);
						printf("\tTX: Complete.\n");
					}else if(server_sync_packet.mtime > sync_packet.mtime){ //Server has a more recent version.
						printf("TX: Get file: %s\n", file->d_name);
						get_file(soc, directory, server_sync_packet.filename, server_sync_packet.size, server_sync_packet.mtime);
						printf("\tTX complete: Updating file %s.\n", server_sync_packet.filename);						
					}
				}
	
				file_count++; 
		}

		if(closedir(dir) == -1){
			perror("Closing directory: ");
			exit(1);
		}

		/* Once all files in this directory have been checked for their synchronization,
		 * check if the server has any new files, which this client does not and retrieve
		 * them if so.
		 */
		retrieve_new_files(soc, directory);

		printf("INFO: Sleeping\n");
		//Sleep for WAITTIME.
		sleep(WAITTIME);
	}

	Close(soc);	
}
Ejemplo n.º 28
0
int main(int argc, char* argv[]) {

    struct sockaddr_in sad; // structure to hold an IP address
    struct sockaddr_in cad; // structure to hold an IP address

    struct addrinfo hint;
    struct addrinfo *serverptr;

    int	sd, sd2;		     // socket descriptor
    int	port;		     // protocol port number
    char	*host;		     // pointer to host name
    char	buf[BUFSIZE];	     // buffer for data from the server
    char buf2[BUFSIZE];
    int   bytes_expected;

    int alen;

    memset((char *)&sad,0,sizeof(sad)); // clear sockaddr structure
    sad.sin_family = AF_INET;	      // set family to Internet

    int i;
    for(i = 65; i < BUFSIZE + 65; i++)
        buf2[i-65] = i % 256;

    if (argc < 3) {
        printf("usage: %s [ host ] [ port ]\n",argv[0]);
        exit(-1);
    }

    host = argv[1];
    port = atoi(argv[2]);

    if (port <= 0) {
        fprintf(stderr,"SOURCE: bad port number %s\n",argv[2]);
        exit(1);
    }

    //  prepare the hint information
    bzero(&hint, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_family = AF_INET;

    Getaddrinfo(host, NULL, &hint, &serverptr);

    bcopy(serverptr->ai_addr, (char *)&sad, serverptr->ai_addrlen);

    sad.sin_port = htons((u_short)port);

    // Create a socket.
    sd = Socket(AF_INET, SOCK_STREAM, 0);

    //Bind the socket to the specififed port
    Bind(sd, (struct sockaddr *) &sad, sizeof(sad));

    printf("SINK: Socket created\n");

    listen(sd, 5);
    alen = sizeof(cad);

    printf("SINK: Waiting for a connection\n");

    sd2 = accept(sd, (struct sockaddr *) &cad, &alen);

    printf("SINK: Waiting to receive a message\n");

    Readn(sd2, &bytes_expected, sizeof(int));
    Readn(sd2, buf2, bytes_expected+1);

    printf("SINK: Received a message\n");
    printf("SINK: (%d) '%s'\n", bytes_expected, buf2);

    Readn(sd2, &bytes_expected, sizeof(int));
    Readn(sd2, buf2, bytes_expected+1);

    printf("SINK: Received a message\n");
    printf("SINK: (%d) '%s'\n", bytes_expected, buf2);

    printf("SINK: Responding to Source\n");

    strcpy(buf, "message recieved");
    bytes_expected = strlen(buf);

    Writen(sd, &bytes_expected, sizeof(int));
    Writen(sd, buf, bytes_expected);

    close(sd2);
    close(sd);
    return 1;
}
Ejemplo n.º 29
0
int thread_For_Read_Write (int *psocketfd)
{
	int newsocketfd;
	int n, nread, nwrite;
	char bufscrittura[LENVETLETTURA];
	char buflettura[LENVETSCRITTURA];
	int *ptr;
	unsigned int sum;

	newsocketfd=*psocketfd;
	free(psocketfd);
	psocketfd=NULL;

	/* alloco la struttura in cui restituire il risultato */
	ptr=malloc(sizeof(int));
	if(ptr==NULL) {
		perror("malloc failed: ");
		fflush(stderr);
		pthread_exit (NULL);
		return(0);
	}

	sum=inizializza(bufscrittura,LENVETLETTURA);
	printf("inizializza somma vettore %d\n", sum );
	
	/*
		stampavet(bufscrittura,LENVETLETTURA);
		fflush (stdout);
	*/
	
	sum=htonl(sum);
	/* scrittura della somma del vettore */
	nwrite = sizeof(int);
	printf ("Writen()\n");
	fflush (stdout);
	n = Writen (newsocketfd, (char*)&sum, nwrite );
	if (n != nwrite)
	{
		printf ("Writen() sum failed");
		fflush(stdout);
		*ptr=0;
		pthread_exit ( ptr );  /* valore restituito dal thread */
		return (0);
	}
	
	/* lettura */
	nread=LENVETSCRITTURA;
	printf ("Readn() thread\n");
	fflush (stdout);
	n = Readn (newsocketfd, buflettura, nread);

	/*printf("n di read thread %d", n);*/
	if (n != nread)
	{
		printf ("Readn()thread failed \n");
		fflush(stdout);
		*ptr=0;
		pthread_exit ( ptr );  /* valore restituito dal thread */
		return (0);
	}
	
	/* scrittura */
	nwrite = LENVETLETTURA;
	printf ("Writen()\n");
	fflush (stdout);
	n = Writen (newsocketfd, bufscrittura, nwrite );
	if (n != nwrite)
	{
		printf ("Writen() failed \n");
		fflush(stdout);
		*ptr=0;
		pthread_exit ( ptr );  /* valore restituito dal thread */
		return (0);
	}

	/* chiusura */
	printf ("terminazione corretta del pthread\n");
	fflush (stdout);
	*ptr=1;
	pthread_exit ( ptr );  /* valore restituito dal thread */
	return (1);
}
Ejemplo n.º 30
0
int main(int argc,char **argv)
{
	int i,maxi,maxfd,listenfd,connfd,sockfd;
	int nready,open_max;
	ssize_t n;
	char buf[MAXLINE];
	socklen_t clilen;
	open_max = sysconf(_SC_OPEN_MAX);
	struct pollfd client[open_max];
	struct sockaddr_in cliaddr,servaddr;

	listenfd = Socket(AF_INET,SOCK_STREAM,0);

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	Bind(listenfd,(SA *)&servaddr,sizeof(servaddr));

	Listen(listenfd,LISTENQ);

	client[0].fd = listenfd;
	client[0].events = POLLRDNORM;
	for(i=1;i < open_max;i++)
		client[i].fd = -1;		/* -1 indicates available entry */
	maxi = 0;					/* maxi index into client[] entry */

	for( ; ; ){
		nready = Poll(client,maxi + 1,INFTIM);

		if(client[0].revents & POLLRDNORM){		/* new connection */
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd,(SA *)&cliaddr,&clilen);

			for(i = 1;i < open_max;i++)
				if(client[i].fd < 0){
					client[i].fd = connfd;		/* save descriptor */
					break;
				}
			if(i == open_max)
				err_quit("too many clients");

			client[i].events = POLLRDNORM;
			if(i > maxi)
				maxi = i;		/* max index in client[] array */

			if(--nready <= 0)
				continue;		/* no more readable descriptors */
		}

		for(i = 1;i <= maxi;i++){		/* check all clients for data */
			if( (sockfd = client[i].fd) < 0)
				continue;
			if(client[i].revents & (POLLRDNORM | POLLERR)){
				if( (n = Read(sockfd,buf,MAXLINE)) < 0){
					if(errno == ECONNRESET){
						/* connection reset by client */
						Close(sockfd);
						client[i].fd = -1;
					}else
						err_sys("read error");
				}else if(n == 0){
					/* connection closed by client */
					Close(sockfd);
					client[i].fd = -1;
				}else
					Writen(sockfd,buf,n);

				if(--nready <= 0)
					break;			/* no more readable descriptors */
			}
		}
	}
}