Beispiel #1
0
void mexFunction(int nlhs,       mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  char buf[MAXLENGTH];
  char numStr[20];
  double value;
  double *pvals,*pind;
  int i,j,numRobots,numDOF;
  int sockd;
  mxArray *vals;

  /* Check for proper number of arguments */
  
  if (nrhs > 1) {
    mexErrMsgTxt("getDOFVals takes at most one input argument.");
  } else if (nlhs > 1) {
    mexErrMsgTxt("getDOFVals takes one output argument.");
  }
  if (nlhs == 0 ) nlhs=1;

  sockd = ConnectTo("localhost",4765);

  if (sockd < 0)
    mexErrMsgTxt("Could not connect");
 
  strcpy(buf,"getDOFVals ");

  // if no robots were specified by user, read total number of robots
  if (nrhs==0) {
	strcat(buf,"ALL\n");
	Writeline(sockd,buf,strlen(buf));

    Readline(sockd,buf,MAXLENGTH);
    sscanf(buf,"%d\n",&numRobots);
  }
  // otherwise send the body list
  else {
	numRobots = mxGetNumberOfElements(prhs[0]);
	if (numRobots>0) {
	  sprintf(numStr,"%d ",numRobots);
	  strcat(buf,numStr);

	  pind = mxGetPr(prhs[0]);
	  for (i=0;i<numRobots-1;i++) {
	    sprintf(numStr,"%d ",(int)pind[i]-1);
  		strcat(buf,numStr);
	  }
	  sprintf(numStr,"%d\n",(int)pind[i]-1);
	  strcat(buf,numStr);
	  Writeline(sockd,buf,strlen(buf));
	}
  }

  if (numRobots == 0) {
	plhs[0] = NULL;
	plhs[0] = NULL;
  }
  else {
	if (numRobots > 1){
	  for (i=0;i<nlhs;i++)
        plhs[i] = mxCreateCellArray(1,&numRobots);
    }
	
    for (i=0;i<numRobots;i++) {
	  Readline(sockd,buf,MAXLENGTH);
	   if (!strncmp(buf,"Error",5)) {
		mexErrMsgTxt(buf);
		break;
	  }

      sscanf(buf,"%d\n",&numDOF);
	  sprintf(buf,"NumDOF read: %d",numDOF);

	  if (numDOF == 0) {
		vals = mxCreateScalarDouble(0);
	  }
	  else {
	    vals = mxCreateDoubleMatrix(numDOF,1,mxREAL);
	    pvals = mxGetPr(vals);
      }
      for (j=0;j<numDOF;j++) {
        Readline(sockd,buf,MAXLENGTH);
        sscanf(buf,"%lf\n",&value);
        pvals[j] = value;
	  }
	  if (numRobots == 1) {
		plhs[0] = vals;
	  } else {
	    mxSetCell(plhs[0],i,vals);
	  }
	}
  }

  CloseConnection(sockd);
  return;
}
Beispiel #2
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;
  
}
Beispiel #3
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);
		
	}
}
Beispiel #4
0
void str_cli(FILE *file,int sockfd)
{
	fd_set rset;
	int nread,maxfd,flag;
	char sendline[MAXLINE],recvline[MAXLINE];
	flag = 1;
	
	FD_ZERO(&rset);
	maxfd = max(fileno(file),sockfd);
	for(;;)
	{
		FD_SET(sockfd,&rset);
		if(flag)
			FD_SET(fileno(file),&rset);
		if(select(maxfd+1,&rset,NULL,NULL,NULL) <0)
			err_quit("select error!");
		
		if(FD_ISSET(fileno(file),&rset)
		{
			if(Fgets(sendline,MAXLINE,file) == NULL)
			{
				flag = 0;
				shutdown(sockfd,SHUT_WR);
				FD_CLR(fileno(file),&rset);
				continue;
			}else
				Writen(sockfd,sendline,strlen(buffer));
		}
		
		if(FD_ISSET(sockfd,&rset))
		{
			if(Readline(sockfd,recvline,MAXLINE) == 0)
			{
				if(flag == 0)
					break;
				else
					err_quit("str_cli:server terminated prematurely");
			}
			Fputs(recvline,file);
		}
	}

void str_cli(FILE *file,int sockfd)
{
	fd_set rset;
	int nread,maxfd,flag;
	char sendline[MAXLINE],recvline[MAXLINE];
	flag = 1;
	
	FD_ZERO(&rset);
	maxfd = max(fileno(file),sockfd);
	for(;;)
	{
		FD_SET(sockfd,&rset);
		if(flag)
			FD_SET(fileno(file),&rset);
		if(select(maxfd+1,&rset,NULL,NULL,NULL) <0)
			err_quit("select error!");
		
		if(FD_ISSET(fileno(file),&rset)
		{
			if(Fgets(sendline,MAXLINE,file) == NULL)
			{
				flag = 0;
				shutdown(sockfd,SHUT_WR);
				FD_CLR(fileno(file),&rset);
				continue;
			}else
				Writen(sockfd,sendline,strlen(buffer));
		}
		
		if(FD_ISSET(sockfd,&rset))
		{
			if(Readline(sockfd,recvline,MAXLINE) == 0)
			{
				if(flag == 0)
					break;
				else
					err_quit("str_cli:server terminated prematurely");
			}
			Fputs(recvline,file);
		}
	}
}
Beispiel #5
0
int main(int argc, char *argv[]) {
    int       list_s;                /*  listening socket          */
    int       conn_s;                /*  connection socket         */
    short int port;                  /*  port number               */
    struct    sockaddr_in servaddr;  /*  socket address structure  */
    char      buffer[MAX_LINE];      /*  character buffer          */
    char     *endptr;                /*  for strtol()              */


    /*  Get port number from the command line, and
        set to default port if no arguments were supplied  */

    if ( argc == 2 ) {
	port = strtol(argv[1], &endptr, 0);
	if ( *endptr ) {
	    fprintf(stderr, "ECHOSERV: Invalid port number.\n");
	    exit(EXIT_FAILURE);
	}
    }
    else if ( argc < 2 ) {
	port = ECHO_PORT;
    }
    else {
	fprintf(stderr, "ECHOSERV: Invalid arguments.\n");
	exit(EXIT_FAILURE);
    }

	
    /*  Create the listening socket  */

    if ( (list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
	fprintf(stderr, "ECHOSERV: Error creating listening socket.\n");
	exit(EXIT_FAILURE);
    }


    /*  Set all bytes in socket address structure to
        zero, and fill in the relevant data members   */

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(port);


    /*  Bind our socket addresss to the 
	listening socket, and call listen()  */

    if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) {
	fprintf(stderr, "ECHOSERV: Error calling bind()\n");
	exit(EXIT_FAILURE);
    }

    if ( listen(list_s, LISTENQ) < 0 ) {
	fprintf(stderr, "ECHOSERV: Error calling listen()\n");
	exit(EXIT_FAILURE);
    }

    
    /*  Enter an infinite loop to respond
        to client requests and echo input  */

    while ( 1 ) {

	/*  Wait for a connection, then accept() it  */

	if ( (conn_s = accept(list_s, NULL, NULL) ) < 0 ) {
	    fprintf(stderr, "ECHOSERV: Error calling accept()\n");
	    exit(EXIT_FAILURE);
	}


	/*  Retrieve an input line from the connected socket
	    then simply write it back to the same socket.     */

	Readline(conn_s, buffer, MAX_LINE-1);
	Writeline(conn_s, buffer, strlen(buffer));


	/*  Close the connected socket  */

	if ( close(conn_s) < 0 ) {
	    fprintf(stderr, "ECHOSERV: Error calling close()\n");
	    exit(EXIT_FAILURE);
	}
    }
}
Beispiel #6
0
 iterator& operator++() {
     Readline();
     return *this;
 }
Beispiel #7
0
int Get_Request(int conn, struct ReqInfo * reqinfo) {

    char   buffer[MAX_REQ_LINE] = {0};
    int    rval;
    fd_set fds;
    struct timeval tv;


    /*  Set timeout to 5 seconds  */

    tv.tv_sec  = 5;
    tv.tv_usec = 0;


    /*  Loop through request headers. If we have a simple request,
	then we will loop only once. Otherwise, we will loop until
	we receive a blank line which signifies the end of the headers,
	or until select() times out, whichever is sooner.                */

    do {

        /*  Reset file descriptor set  */

        FD_ZERO(&fds);
        FD_SET (conn, &fds);


        /*  Wait until the timeout to see if input is ready  */
        rval = select(conn + 1, &fds, NULL, NULL, &tv);


        /*  Take appropriate action based on return from select()  */

        if ( rval < 0 ) {
            Error_Quit("Error calling select() in get_request()");
        }
        else if ( rval == 0 ) {

            /*  input not ready after timeout  */

            return -1;

        }
        else {
            /*  We have an input line waiting, so retrieve it  */
            Readline(conn, buffer, MAX_REQ_LINE - 1);
            Trim(buffer);

            if ( buffer[0] == '\0' ){
                break;
            }

            if ( Parse_HTTP_Header(buffer, reqinfo) ){
                fprintf(stderr, "Error in Parse_HTTP_Header\n");
                break;
            }
        }

    } while ( reqinfo->type != SIMPLE );

    /* get request body if any */
    if(reqinfo->contentlength){
        fprintf(stderr, "  Request Content-Length: %d\n", reqinfo->contentlength);
        Get_Request_Body(conn, reqinfo, reqinfo->contentlength);
    }

    return 0;
}
Beispiel #8
0
int main(int argc, char *argv[]) {
    int       list_s;                /*  listening socket          */
    int       conn_s;                /*  connection socket         */
    short int port;                  /*  port number               */
    struct    sockaddr_in servaddr;  /*  socket address structure  */
    char      buffer[MAX_LINE];      /*  character buffer          */
    char     *endptr;                /*  for strtol()              */

	fprintf(stdout, "Starting ECHOServer.\n");
    /*  Get port number from the command line, and
        set to default port if no arguments were supplied  */

    if ( argc == 2 ) {
		port = strtol(argv[1], &endptr, 0);
		if ( *endptr ) {
			fprintf(stderr, "ECHOSERV: Invalid port number.\n");
			exit(EXIT_FAILURE);
		}
    }else if ( argc < 2 ) {
		port = ECHO_PORT;
    }else{
		fprintf(stderr, "ECHOSERV: Invalid arguments.\n");
		exit(EXIT_FAILURE);
    }

	printf("SysLoadModule(NET)=%d\n", SysLoadModule(SYSMODULE_NET));
    printf("net_init()=%d\n", net_initialize_network());

    /*  Create the listening socket  */

    if ( (list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error creating listening socket.\n");
		printf("errno: %d\n", errno);
		exit(EXIT_FAILURE);
    }


    /*  Set all bytes in socket address structure to
        zero, and fill in the relevant data members   */

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(port);


    /*  Bind our socket addresss to the 
	listening socket, and call listen()  */

    if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error calling bind()\n");
		exit(EXIT_FAILURE);
    }

    if ( listen(list_s, LISTENQ) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error calling listen()\n");
		exit(EXIT_FAILURE);
    }
    char* message = "Welcome to ECHOServer test.\nType exit and hit enter to close app, otherwise type anything you want and hit enter and I will replay it back to you free of charge. :)";
    /*  Enter an infinite loop to respond
        to client requests and echo input  */
	int run = 1;
    while ( run ) {

		/*  Wait for a connection, then accept() it  */

		if ( (conn_s = accept(list_s, NULL, NULL) ) < 0 ) {
			fprintf(stderr, "ECHOSERV: Error calling accept()\n");
			exit(EXIT_FAILURE);
		}

		Writeline(conn_s, message, strlen(message));

		/*  Retrieve an input line from the connected socket
			then simply write it back to the same socket.     */

		Readline(conn_s, buffer, MAX_LINE-1);
		if(strncmp("exit", buffer, 4) == 0)
			run = 0;
		Writeline(conn_s, buffer, strlen(buffer));


		/*  Close the connected socket  */

		if ( closesocket(conn_s) < 0 ) {
			fprintf(stderr, "ECHOSERV: Error calling closesocket()\n");
			exit(EXIT_FAILURE);
		}

    }
	net_finalize_network();
	SysUnloadModule(SYSMODULE_NET);
}
int main(int argc,char *argv[])
{

        struct addrinfo criteria,*info_server,*local_info;
        int addr_ret;
        int fd,conn_fd;
        char buf[100];
        char rcvbuf[4096];
        char sendbuf[4096];
        fd_set read_set;
	char temp_buf[4096];
        memset(&criteria,0,sizeof(criteria));
        criteria.ai_family = AF_UNSPEC;
        criteria.ai_socktype = SOCK_STREAM;
        criteria.ai_flags = AI_PASSIVE;
        if (argc != 3){
                send_msg_to_parent("pass right parameters",EXIT_FAILURE);
                exit(1);

        }
        parentfd = atoi(argv[2]);
        addr_ret = getaddrinfo(argv[1],port,&criteria,&info_server);
        if (addr_ret != 0){
		send_msg_to_parent("getaddrinfo failed",EXIT_FAILURE);
        }

        for (local_info = info_server;local_info != NULL;local_info = local_info->ai_next){
                fd = socket(local_info->ai_family,local_info->ai_socktype,local_info->ai_protocol);
                if (fd == -1){
                        printf("\n error in socket command");
                        continue;
                }

                int b = connect(fd,(SA *)info_server->ai_addr,info_server->ai_addrlen);
                if (b == -1){
                        close(fd);
                        printf(" \n connect error");
                        continue;
                }
                break;
        }

        freeaddrinfo(info_server);

        if (local_info == NULL){
                printf("client failed to connect");
                exit(1);

        }
        if (signal(SIGINT,(Sigfunc *)signal_handler) == SIG_ERR)  {
                send_msg_to_parent("signal error",EXIT_FAILURE);
	}
	signal(SIGTERM,(Sigfunc *)signal_handler);

	 int max_fd = fd + 1;
        FD_ZERO(&read_set);
        for(;;){
		//Select to monitor STDIN and output from Server
                FD_SET(fileno(stdin),&read_set);
                FD_SET(fd,&read_set);
		//Since stdin is 1, thus max_fd = fd+1
               int sel_ret = select(max_fd,&read_set,NULL,NULL,NULL);
                if (sel_ret < 0) {
                        send_msg_to_parent("select error",EXIT_FAILURE);

                }
                if (FD_ISSET(fileno(stdin),&read_set)){
                        char new_buf[4096];
			memset(sendbuf,0,4096);
                        if (fgets(sendbuf,4096,stdin) != NULL) {
				 if (sendbuf == NULL || *sendbuf == EOF || sendbuf ==0){

					send_msg_to_parent("Terminated with cntrl+d",EXIT_SUCCESS); 
				}  
                                int msg_len = strlen(sendbuf);
				if (msg_len == 0)  {
					printf("cntrl+d hit \n");
				}
			        printf(" \n Please dont write in time client window \n");	
                        } else {
				//printf("cntrl d hit fgets null");
 				send_msg_to_parent("Client terminated by cntrl+d",EXIT_SUCCESS);
                        }
                }
		//When output received from server
                if (FD_ISSET(fd,&read_set)) {
                        if ( Readline(fd,rcvbuf,4096) > 0 ) {
				printf("Server Message :");
                                if (fputs(rcvbuf,stdout) == EOF) {
                                        send_msg_to_parent("fputs and output error",EXIT_FAILURE);
                                }
                        } else {
                                send_msg_to_parent("sever not responding",EXIT_FAILURE);

                        }
                }

        }
        return 0; 

}
Beispiel #10
0
int main(int argc, char **argv) {
    char *hostAddr, *msg;
    char sendBuf[MAXLINE], recvBuf[MAXLINE];
    struct sockaddr_in servAddr;
    int sockfd, len;
    fd_set readfds;
    int maxfd;

    if (argc != 3) {
        writeMsgAndExit("Invalid Arguments", EXIT_FAILURE);
    }

    hostAddr = argv[1];
    writefd = atoi(argv[2]);

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        writeMsgAndExit("socket error", EXIT_FAILURE);
    }

    bzero(&servAddr, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_port   = htons(ECHO_PORT);

    if (inet_pton(AF_INET, hostAddr, &servAddr.sin_addr) <= 0) {
        writeMsgAndExit("inet_pton error", EXIT_FAILURE);
    }

    //TODO: Make socket non-blocking
    if (connect(sockfd, (SA *) &servAddr, sizeof(servAddr)) < 0) {
        writeMsgAndExit("socket connect error", EXIT_FAILURE);
    }
    printf("Client succefully connected to server (%s)\n", hostAddr);

    if (signal(SIGINT, sig_int) == SIG_ERR) {
        writeMsgAndExit("signal error", EXIT_FAILURE);
    }

    maxfd = sockfd + 1;
    FD_ZERO(&readfds);
    while (1) {
        FD_SET(fileno(stdin), &readfds);
        FD_SET(sockfd, &readfds);
        if (select(maxfd, &readfds, NULL, NULL, NULL) < 0) {
            writeMsgAndExit("select error on stdin and sockfd", EXIT_FAILURE);
        }

        if (FD_ISSET(fileno(stdin), &readfds)) {
            if (Fgets(sendBuf, MAXLINE, stdin) != NULL) {
                len = strlen(sendBuf);
                if (writen(sockfd, sendBuf, len) != len) {
                    writeMsgAndExit("writen error", EXIT_FAILURE);
                }
            } else {
                writeMsgAndExit("Terminated Successfully", EXIT_SUCCESS);
            }
        }
        if (FD_ISSET(sockfd, &readfds)) {
            if (Readline(sockfd, recvBuf, MAXLINE) > 0) {
                if (fputs(recvBuf, stdout) == EOF) {
                    writeMsgAndExit("fputs stdout error", EXIT_FAILURE);
                }
            } else {
                writeMsgAndExit("Server Crash", EXIT_FAILURE);
            }
        }
    }

    return 0;
}
Beispiel #11
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);
				
			} 
	} 
}
Beispiel #12
0
int main(int argc, char *argv[]) {

    int       conn_s;                /*  connection socket         */
    short int port;                  /*  port number               */
    struct    sockaddr_in servaddr;  /*  socket address structure  */
    char      buffer[MAX_LINE];      /*  character buffer          */
    char     *szAddress;             /*  Holds remote IP address   */
    char     *szPort;                /*  Holds remote port         */
    char     *endptr;                /*  for strtol()              */


    /*  Get command line arguments  */

    ParseCmdLine(argc, argv, &szAddress, &szPort);


    /*  Set the remote port  */

    port = strtol(szPort, &endptr, 0);
    if ( *endptr ) {
	printf("ECHOCLNT: Invalid port supplied.\n");
	exit(EXIT_FAILURE);
    }
	

    /*  Create the listening socket  */

    if ( (conn_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
	fprintf(stderr, "ECHOCLNT: Error creating listening socket.\n");
	exit(EXIT_FAILURE);
    }


    /*  Set all bytes in socket address structure to
        zero, and fill in the relevant data members   */

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_port        = htons(port);


    /*  Set the remote IP address  */

    if ( inet_aton(szAddress, &servaddr.sin_addr) <= 0 ) {
	printf("ECHOCLNT: Invalid remote IP address.\n");
	exit(EXIT_FAILURE);
    }

    
    /*  connect() to the remote echo server  */

    if ( connect(conn_s, (struct sockaddr *) &servaddr, sizeof(servaddr) ) < 0 ) {
	printf("ECHOCLNT: Error calling connect()\n");
	exit(EXIT_FAILURE);
    }


    /*  Get string to echo from user  */

    printf("Enter the string to echo: ");
    fgets(buffer, MAX_LINE, stdin);
    

    /*  Send string to echo server, and retrieve response  */

    Writeline(conn_s, buffer, strlen(buffer));
    Readline(conn_s, buffer, MAX_LINE-1);


    /*  Output echoed string  */

    printf("Echo response: %s\n", buffer);

    return EXIT_SUCCESS;
}
Beispiel #13
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 */
				}
			
		}
    }
}
Beispiel #14
0
static void handleclient(u64 conn_s_p)
{
	int conn_s = (int)conn_s_p;
	int list_s_data = -1;
	int conn_s_data = -1;
	
	char	cwd[2048];
	char	login_user[32];
	char	login_pass[64];
	char	rename_from[2048];
	u32	rest = 0;
	int	authd = 0;
	
	char	message[4096];
	char	buffer[2048];
	
	sprintf(cwd, "/");
	
	sprintf(message, "220-OpenPS3FTP by @jjolano\r\n");
	Writeline(conn_s, message, strlen(message));
	
	sprintf(message, "220 Version %s\r\n", VERSION);
	Writeline(conn_s, message, strlen(message));
	
	while(program_running == 1)
	{
		sys_ppu_thread_yield();
		
		if(Readline(conn_s, buffer, 2047) == 0 || strncmp(buffer, "QUIT", 4) == 0 || strncmp(buffer, "BYE", 3) == 0)
		{
			break;
		}
		
		buffer[strcspn(buffer, "\n")] = '\0';
		buffer[strcspn(buffer, "\r")] = '\0';
		
		if(strncmp(buffer, "USER", 4) == 0)
		{
			if(strlen(buffer) > 7)
			{
				strcpy(login_user, buffer+5);
				
				sprintf(message, "331 Username %s OK. Password required\r\n", login_user);
				Writeline(conn_s, message, strlen(message));
			}
			else
			{
				sprintf(message, "430 No username specified\r\n");
				Writeline(conn_s, message, strlen(message));
			}
		}
		else if(strncmp(buffer, "PASS", 4) == 0)
		{
			if(strlen(buffer) > 7)
			{
				strcpy(login_pass, buffer+5);
				
				if(strcmp(LOGIN_USERNAME, login_user) == 0 && strcmp(LOGIN_PASSWORD, login_pass) == 0)
				{
					authd = 1;
					sprintf(message, "230 Successful authentication\r\n");
				}
				else
				{
					sprintf(message, "430 Invalid username or password\r\n");
					Writeline(conn_s, message, strlen(message));
				}
			}
			else
			{
				sprintf(message, "430 Invalid username or password\r\n");
			}
			
			Writeline(conn_s, message, strlen(message));
		}
		else if(authd == 0)
		{
			sprintf(message, "530 Not logged in\r\n");
			Writeline(conn_s, message, strlen(message));
		}
		else if(strncmp(buffer, "FEAT", 4) == 0)
		{
			sprintf(message, "211-Extensions supported:\r\n");
			Writeline(conn_s, message, strlen(message));
			
			sprintf(message, " SIZE\r\n");
			Writeline(conn_s, message, strlen(message));
			sprintf(message, " PASV\r\n");
			Writeline(conn_s, message, strlen(message));
			
			
			sprintf(message, "211 End\r\n");
			Writeline(conn_s, message, strlen(message));
		}
		else if(strncmp(buffer, "TYPE", 4) == 0)
		{
			sprintf(message, "200 TYPE is now %s\r\n", buffer+5);
			Writeline(conn_s, message, strlen(message));
		}
		else if(strncmp(buffer, "PORT", 4) == 0)
		{
			rest = 0;
			
			char connectinfo[24];
			strcpy(connectinfo, buffer+5);
			
			char data[7][4];
			int len = strlen(connectinfo);
			int i, x = 0, y = 0;
			
			for(i = 0;i < len;i++)
			{
				if(connectinfo[i] == ',')
				{
					data[x][y] = '\0';
					x++;
					y = 0;
				}
				else
				{
					data[x][y] =  connectinfo[i];
					y++;
				}
			}
			
			char conn_ipaddr[16];
			sprintf(conn_ipaddr, "%s.%s.%s.%s", data[0], data[1], data[2], data[3]);

			int p1 = atoi(data[4]);
			int p2 = atoi(data[5]);
			
			short int conn_port = (p1 * 256) + p2;
			
			netClose(conn_s_data);
			netClose(list_s_data);
			
			list_s_data = -1;
			conn_s_data = netSocket(AF_INET, SOCK_STREAM, 0);
			
			struct sockaddr_in servaddr;
			memset(&servaddr, 0, sizeof(servaddr));
			servaddr.sin_family	= AF_INET;
			servaddr.sin_port	= htons(conn_port);
			inet_pton(AF_INET, conn_ipaddr, &servaddr.sin_addr);
			
			if(connect(conn_s_data, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0)
			{
				sprintf(message, "200 PORT command successful\r\n");
				Writeline(conn_s, message, strlen(message));
				continue;
			}
			
			sprintf(message, "425 Internal Error\r\n");
			Writeline(conn_s, message, strlen(message));
		}
		else if(strncmp(buffer, "PASV", 4) == 0)
		{
			rest = 0;
			netSocketInfo snf;
			
			int ret = netGetSockInfo(conn_s, &snf, 1);
			
			if(ret >= 0 && snf.local_adr.s_addr != 0)
			{
				netClose(conn_s_data);
				netClose(list_s_data);
				
				conn_s_data = -1;
				list_s_data = -1;
				
				// create the socket
				list_s_data = netSocket(AF_INET, SOCK_STREAM, 0);

				// calculate the passive mode port
				//srand((unsigned)time(NULL));
				//srand((unsigned)time(NULL) + rand());
				
				int rand1 = 4 + rand() % 255;
				int rand2 = rand() % 256;
				
				short int port = (rand1 * 256) + rand2;
				
				struct sockaddr_in servaddr;
				memset(&servaddr, 0, sizeof(servaddr));
				servaddr.sin_family      = AF_INET;
				servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
				servaddr.sin_port        = htons(port);
				
				// bind address to listener, listen, and accept
				netBind(list_s_data, (struct sockaddr *) &servaddr, sizeof(servaddr));
				netListen(list_s_data, LISTENQ);
				sprintf(message, "227 Entering Passive Mode (%u,%u,%u,%u,%i,%i)\r\n",
					(snf.local_adr.s_addr & 0xFF000000) >> 24,
					(snf.local_adr.s_addr & 0xFF0000) >> 16,
					(snf.local_adr.s_addr & 0xFF00) >> 8,
					(snf.local_adr.s_addr & 0xFF),
					rand1, rand2);
				
				Writeline(conn_s, message, strlen(message));
						
				if((conn_s_data = netAccept(list_s_data, NULL, NULL)) < 0)
				{
					printf("warning: failed to accept a connection\n");
					netClose(conn_s_data);
					netClose(list_s_data);
					
					conn_s_data = -1;
					list_s_data = -1;
				}
				else
				{
					// PASV success
					continue;
				}
			}
		
		sprintf(message, "425 Internal Error\r\n");
		Writeline(conn_s, message, strlen(message));
		}
Beispiel #15
0
int main(int argc,char *argv[])
{
	int	listenfd,acceptfd,maxfd,client[MAXSIZE],nread,i,imax;
	char	recvmsg[MAXLINE];
	struct sockaddr sa;
	socklen_t	salen;
	fd_set	rset,rsetsave;

	for(i=0;i<MAXSIZE;i++)
		client[i] = -1;
	listenfd = acceptfd = -1;
	imax = 0;

	if(argc == 2)
		listenfd = Tcp_listen(NULL,argv[1],&salen);
	else if(argc == 3)
		listenfd = Tcp_listen(argv[1],argv[2],&salen);
	else
		err_quit("usage : server02 [<host>] <serv>");

	maxfd = listenfd;
	FD_ZERO(&rsetsave);
	
	FD_SET(listenfd,&rsetsave);
	while(1){
		rset = rsetsave;
		if((nread = select(maxfd+1,&rset,NULL,NULL,NULL)) < 0)
			err_quit("select error");

		if(FD_ISSET(listenfd,&rset)) {
			if((acceptfd = accept(listenfd,&sa,&salen)) < 0) {
				if((errno == EINTR))
					continue;
				else
					err_sys("server02 error in accept!");
			}else {
				for(i=0;i<MAXSIZE;i++){
					if(client[i] < 0){
						client[i] = acceptfd;
						break;
					}
				}

				if(i == MAXSIZE)
					err_quit("reach max client!please wait\n");
				FD_SET(acceptfd,&rsetsave);
				if(acceptfd > maxfd)
					maxfd = acceptfd;
				if(i > imax)
					imax = i;
				if(--nread <= 0)
					continue;
			}
		}

		for(i=0;i<=imax;i++){
			if(client[i] < 0)
				continue;
			if(FD_ISSET(client[i],&rset)) {
				if((Readline(client[i],recvmsg,MAXLINE)) == 0){
					Close(client[i]);
					FD_CLR(client[i],&rsetsave);
					client[i] = -1;
					printf("has disconnect with one socket!\n");
				}else {
					Writen(client[i],recvmsg,strlen(recvmsg));
				}

				if(--nread <= 0)
					continue;
			}
		}
	}
}
Beispiel #16
0
void
CommandShell(void)
{
	int tUsed, bUsed;
	ArgvInfo ai;
	char prompt[64];
	char *lineRead;
#if defined(WIN32) || defined(_WINDOWS)
#else
	int sj;
#endif
	time_t cmdStart, cmdStop;

	/* Execution may jump back to this point to restart the shell. */
#if defined(WIN32) || defined(_WINDOWS)

#elif defined(HAVE_SIGSETJMP)
	sj = sigsetjmp(gBackToTopJmp, 1);
#else	/* HAVE_SIGSETJMP */
	sj = setjmp(gBackToTopJmp);
#endif	/* HAVE_SIGSETJMP */

#if defined(WIN32) || defined(_WINDOWS)
#else
	if (sj != 0) {
		Trace(0, "Caught signal %d, back at top.\n", gGotSig);
		if (gGotSig == SIGALRM) {
			(void) printf("\nRemote host was not responding, closing down the session.");
			FTPShutdownHost(&gConn);
		} else{
			(void) printf("\nInterrupted.\n");
			if (gCancelCtrl != 0) {
				gCancelCtrl = 0;
				(void) printf("Closing down the current FTP session: ");
				FTPShutdownHost(&gConn);
				(void) sleep(1);
				(void) printf("done.\n");
			}
		}
	}

	gMayBackToTopJmp = 1;
#endif


	++gEventNumber;

	while (gDoneApplication == 0) {
#if defined(WIN32) || defined(_WINDOWS)
#else
		(void) NcSignal(SIGINT, BackToTop);
		(void) NcSignal(SIGPIPE, BackToTop);
		(void) NcSignal(SIGALRM, BackToTop);
#endif

		MakePrompt(prompt, sizeof(prompt));

		if (gConn.connected == 0) {
			SetXtermTitle("DEFAULT");
		} else {
			SetXtermTitle("%s - NcFTP", gConn.host);
		}

		lineRead = Readline(prompt);
		if (lineRead == NULL) {
			/* EOF, Control-D */
			(void) printf("\n");
			break;
		}
		Trace(0, "> %s\n", lineRead);
		AddHistory(lineRead);
		for (tUsed = 0;;) {
			(void) memset(&ai, 0, sizeof(ai));
			bUsed = MakeArgv(lineRead + tUsed, &ai.cargc, ai.cargv,
				(int) (sizeof(ai.cargv) / sizeof(char *)),
				ai.argbuf, sizeof(ai.argbuf),
				ai.noglobargv, 0);
			if (bUsed <= 0)
				break;
			tUsed += bUsed;
			if (ai.cargc == 0)
				continue;
			gRunningCommand = 1;
			(void) time(&cmdStart);
			if (DoCommand(&ai) < 0) {
				(void) time(&cmdStop);
				gRunningCommand = 0;
				break;
			}
			(void) time(&cmdStop);
			gRunningCommand = 0;
			if ((cmdStop - cmdStart) > kBeepAfterCmdTime) {
				/* Let the user know that a time-consuming
				 * operation has completed.
				 */
#if defined(WIN32) || defined(_WINDOWS)
				MessageBeep(MB_OK);
#else
				(void) fprintf(stderr, "\007");
#endif
			}
			++gEventNumber;
		}

		free(lineRead);
	}

	CloseHost();
	gMayBackToTopJmp = 0;
}	/* Shell */
Beispiel #17
0
void mexFunction(int nlhs,       mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  char buf[MAXLENGTH];
  char numStr[20];
  double x,y,z,tx,ty,tz;
  double *pwrench,*ploc,*perr,*pind;
  int i,j,numBodies,numContacts;
  int sockd;
  mxArray *wrench,*loc,*err;

  /* Check for proper number of arguments */
  
  if (nrhs > 1) {
    mexErrMsgTxt("get average contacts takes at most one input argument.");
  } else if (nlhs > 3) {
    mexErrMsgTxt("get average contacts takes at most three output arguments.");
  }

  sockd = ConnectTo("localhost",4765);

  if (sockd < 0)
    mexErrMsgTxt("Could not connect");

  // send how many types of date we're collecting
  if (nlhs == 0 ) nlhs=1;
  sprintf(buf,"getContacts %d ",nlhs);

  // if no bodies were specified by user, read total number of bodies
  if (nrhs==0) {
	strcat(buf,"ALL\n");
	Writeline(sockd,buf,strlen(buf));

    Readline(sockd,buf,MAXLENGTH);
    sscanf(buf,"%d\n",&numBodies);
  }
  // otherwise send the body list
  else {
	numBodies = mxGetNumberOfElements(prhs[0]);
	if (numBodies>0) {
	  sprintf(numStr,"%d ",numBodies);
	  strcat(buf,numStr);

	  pind = mxGetPr(prhs[0]);
	  for (i=0;i<numBodies-1;i++) {
	    sprintf(numStr,"%d ",(int)pind[i]-1);
  		strcat(buf,numStr);
	  }
	  sprintf(numStr,"%d\n",(int)pind[i]-1);
	  strcat(buf,numStr);
	  Writeline(sockd,buf,strlen(buf));
	}
  }

  if (numBodies == 0) {
	plhs[0] = NULL;
	plhs[0] = NULL;
  }
  else {
	if (numBodies > 1){
	  for (i=0;i<nlhs;i++)
        plhs[i] = mxCreateCellArray(1,&numBodies);
    }
	
    for (i=0;i<numBodies;i++) {
	  Readline(sockd,buf,MAXLENGTH);
      sscanf(buf,"%d\n",&numContacts);

	  if (numContacts == 0) {
		wrench = mxCreateScalarDouble(0);
		if (nlhs > 1) {loc = mxCreateScalarDouble(0);}
	    if (nlhs > 2) {err = mxCreateScalarDouble(0);}
	  }
	  else {
	    wrench = mxCreateDoubleMatrix(numContacts,6,mxREAL);
	    pwrench = mxGetPr(wrench);
	    if (nlhs > 1) {loc = mxCreateDoubleMatrix(numContacts,3,mxREAL); ploc=mxGetPr(loc);}
	    if (nlhs > 2) {err = mxCreateDoubleMatrix(numContacts,1,mxREAL); perr=mxGetPr(err);}
      }

      for (j=0;j<numContacts;j++) {
        Readline(sockd,buf,MAXLENGTH);
        sscanf(buf,"%lf %lf %lf %lf %lf %lf\n",&x,&y,&z,&tx,&ty,&tz);
        pwrench[j] = x;
        pwrench[numContacts+j] = y;
        pwrench[2*numContacts+j] = z;
        pwrench[3*numContacts+j] = tx;
        pwrench[4*numContacts+j] = ty;
        pwrench[5*numContacts+j] = tz;
		if (nlhs > 1) {
		  Readline(sockd,buf,MAXLENGTH);
		  sscanf(buf,"%lf %lf %lf\n",&x,&y,&z);

  	      ploc[j] = x;
	      ploc[numContacts+j] = y;
	      ploc[2*numContacts+j] = z;
		}
		if (nlhs > 2) {
		  Readline(sockd,buf,MAXLENGTH);
		  sscanf(buf,"%lf\n",perr+j);
        }
	  }
	  if (numBodies == 1) {
		plhs[0] = wrench;
        if (nlhs > 1) plhs[1] = loc;
        if (nlhs > 2) plhs[2] = err;
	  } else {
	    mxSetCell(plhs[0],i,wrench);
	    if (nlhs > 1) mxSetCell(plhs[1],i,loc);
	    if (nlhs > 2) mxSetCell(plhs[2],i,err);
	  }
	}
  }

  CloseConnection(sockd);
  return;

}
int main(int argc,char *argv[]){
	int fd[2];
	char buf[MAXLINE];
	int nread;
	char *input = malloc(sizeof(char)*MAXLINE);
	//Register SIGCHLD
	Signal(SIGCHLD,sig_child);
	fd_set rset;
	struct hostent* host_val;

	//This variable contains the IP address in presentation format. (127.0.0.1)
	char str [INET_ADDRSTRLEN];


	struct in_addr in_addr_val;
	if(argc <2){
		//If invalid request received to execute the program.
		printf("Please enter the IP address or hostname as second argument!\n");
		exit(0);
	}

	if (inet_pton(AF_INET,argv[1],&in_addr_val.s_addr) > 0){
		//If IP address found , print the host name.
		host_val = gethostbyaddr(&in_addr_val.s_addr,4,AF_INET);
		if(host_val != NULL){
			printf("Hostname for the IP address entered is = %s\n",host_val->h_name);
			strcpy(str,argv[1]);
		}else{
			printf("IP address is not found\n");
			exit(0);
		}
	}else{
		//If hostname found , get the IP address and save it in str.
		char *ptr;
		ptr = *++argv;
		host_val = gethostbyname(ptr);
		if(host_val == NULL){
			printf("Host name is not found \n");
			exit(0);
		}else{
			char **pptr = host_val->h_addr_list;
			for ( ; *pptr != NULL; pptr++){
				inet_ntop (host_val->h_addrtype, *pptr, str, sizeof (str));
				printf("IP address for the host name = %s\n",str);
			}
		}

	}

	while(1){
		FD_SET(0,&rset);
		int maxfd1 = 1;
		printf("\nType \"echo\" to start a echo client. \n");
		printf("Type \"time\" to start a daytime client. \n");
		printf("Type \"quit\" to terminate. \n");
		Select(maxfd1,&rset,NULL,NULL,NULL);
		//If input from the user received on stdin.
		if(FD_ISSET(0,&rset)){
			Readline(0,input,MAXLINE);

			if(strncmp(input,"quit",strlen(input)-1) == 0){
				printf("Terminating!!!!\n");
				exit(0);
			}

			pipe(fd);
			pid_t pid;
			pid = fork();
			if(pid == 0){
				//Close the read end from the child.
				close(fd[0]);
				char s[10];
				sprintf(s,"%d",fd[1]);
				if(strncmp(input,"echo",strlen(input)-1) == 0){
					execlp("xterm","xterm","-e","./echo_cli",&str,s,NULL);
				}else if(strncmp(input,"time",strlen(input)-1) == 0){
					execlp("xterm","xterm","-e","./time_cli",&str,s,NULL);
				}else{
					exit(0);
				}

			}else{
				//Close the write end of the pipe.
				close(fd[1]);
				int nread;
				int status;
				bzero(buf,sizeof(buf));

				//Read the feedback from the child.
				while((nread = read(fd[0],&buf,MAXLINE)) > 0){
					Write(1,buf,MAXLINE);
					bzero(buf,sizeof(buf));
				}

				//If client has terminated.
				if(nread == 0){
					printf("[Echo][Client] Client Terminates\n");
				}
				if(nread < 0){

				}
				close(fd[0]);

			}
		}
	}
	return 0;
}
Beispiel #19
0
void 
CreamConnection(creamConnection_t *connection)
{ 
/*
startnotify 	controls the normal operation in PollDB
startnotifyjob 	is used to send notification of jobs contained in joblist_string 
firstnotify 	controls if NTFDATE/END has to be sent (together with sentendonce)
sentendonce 	controls if NTFDATE/END has to be sent (is used to permit STARTNOTIFYJOBLIST to be used during
            	normal notifier operation without sending NTFDATE/END). It is reset to TRUE only by CREAMFILTER command
            	otherwise it remains FALSE after the first notification (finished with NTFDATE/END).
creamisconn 	starts all the normal usage: without it no notifications are sent to cream

So the initial commands should be:
CREAMFILTER
PARSERVERSION

STARTNOTIFY 
or 
STARTNOTIFYJOBLIST
STARTNOTIFYJOBEND

during the normal usage to have info about a list of job:
STARTNOTIFYJOBLIST
STARTNOTIFYJOBEND

*/

	char *buffer;
	int  conn_c = connection->socket_fd;

	if((buffer=calloc(LISTBUFFER,1)) == 0){
		sysfatal("can't malloc buffer in CreamConnection: %r");
	}

	while (Readline(conn_c, buffer, LISTBUFFER-1) > 0) {
		if(strlen(buffer) > 0)
		{
			do_log(debuglogfile, debug, 1, "Received for Cream:%s\n", buffer);
			if (strstr(buffer,"STARTNOTIFY/") != NULL) {
				NotifyStart(buffer, &(connection->lastnotiftime));
				connection->startnotify=TRUE;
				connection->firstnotify=TRUE;
			} else if (strstr(buffer,"STARTNOTIFYJOBLIST/") != NULL) {
				GetJobList(buffer, &(connection->joblist_string));
				connection->startnotifyjob = TRUE;
				connection->startnotify = FALSE;
			} else if (strstr(buffer,"STARTNETWORKSYNC/") != NULL) {
				GetJobList(buffer, &(connection->joblist_string));
				connection->startnotifyjob = TRUE;
				connection->startnotify = FALSE;
			} else if (strstr(buffer,"STARTNOTIFYJOBEND/") != NULL) {
				connection->firstnotify=TRUE;
				connection->lastnotiftime = time(NULL);
			} else if (strstr(buffer,"CREAMFILTER/") != NULL) {
				GetFilter(buffer, connection->socket_fd, &(connection->creamfilter));
				connection->creamisconn=TRUE;
				connection->sentendonce=TRUE;
			} else if (strstr(buffer,"PARSERVERSION/") != NULL) {
				GetVersion(connection->socket_fd);
			}
		}
	}
	connection->creamisconn=FALSE;
	close(conn_c);
	free(buffer);
	connection->socket_fd = 0;
	if (connection->creamfilter) 
	{
		free(connection->creamfilter);
		connection->creamfilter = NULL;
	}
}
Beispiel #20
0
int
main(int argc, char **argv)
{
    int sockfd, maxfd, activity, use_udp = 0;
    fd_set sread;
    char recvline[LINE_MAX];
    char sendline[LINE_MAX];
    char error[LINE_MAX];
    struct sockaddr_in servaddr;
    struct sockaddr local;
    struct timeval timeout;
    socklen_t slen;

    if (argc != 4) {
        snprintf(error, sizeof(error) - 1,
                 "uso: %s <IPaddress> <Port> <Protocol>", argv[0]);
        perror(error);
        exit(EXIT_FAILURE);
    }

    use_udp = strcmp(argv[3], "udp") == 0;

    /* Cria o socket */
    sockfd = use_udp ? Socket(AF_INET, SOCK_DGRAM, 0) :
                       Socket(AF_INET, SOCK_STREAM, 0);

    /* Constroi o endereco de internet do servidor */
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));

    /* Converte string em uma struct de endereco de internet */
    Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

    /* Cria a conexao tcp com o servidor */
    if (!use_udp)
        Connect(sockfd, &servaddr, sizeof(servaddr));

    /* Inicializa os fd_sets */
    FD_ZERO(&sread);

    /* Diz para stdin bufferizar de linha em linha */
    setvbuf(stdin, NULL, _IOLBF, 0);//LINE_MAX);

    int stdineof = 0;
    timeout.tv_sec = 60; // 1 min
    timeout.tv_usec = 0;
    slen = sizeof(local);

    while (1) {
        /* Inserindo fd's nos fd_sets apropriados */
        if (!stdineof)
            FD_SET(fileno(stdin), &sread);
        FD_SET(sockfd, &sread);

        activity = 0;
        maxfd = MAX(sockfd, fileno(stdin)) + 1;
        Select(maxfd, &sread, NULL, NULL, &timeout);

        /* Obtem resposta do servidor */
        if (FD_ISSET(sockfd, &sread)) {
            activity = 1;
            int ret;
            if (use_udp) {
                ret = Recvfrom(sockfd, recvline, LINE_MAX - 1, 0,
                               &local, &slen);
                if (slen != sizeof(servaddr) ||
                    memcmp(&servaddr, &local, slen) != 0) {
                    printf("Resposta ignorada\n");
                    goto read;
                }
            }
            else
                ret = Readline(sockfd, recvline, LINE_MAX);
            if (!ret) {
                if (stdineof)
                    break;
                else {
                    fprintf(stderr, "servidor terminou prematuramente\n");
                    exit(EXIT_FAILURE);
                }
            }
            recvline[ret] = '\0';
            fputs(recvline, stdout);
        }

read:
        /* Le dados da entrada padrao */
        if (FD_ISSET(fileno(stdin), &sread)) {
            activity = 1;
            if (fgets(sendline, LINE_MAX, stdin) == NULL) {
                stdineof = 1;
                if (!use_udp)
                    shutdown(sockfd, SHUT_WR);
                FD_CLR(fileno(stdin), &sread);
                continue;
            }
            use_udp ?
                Sendto(sockfd, sendline, strlen(sendline), 0,
                       (struct sockaddr *)&servaddr, sizeof(servaddr)) :
                Writeall(sockfd, sendline, strlen(sendline));
        }

        /* Tempo espera expirou */
        if (!activity && use_udp)
            break;
    }

    /* Fecha conexao */
    close(sockfd);

    exit(EXIT_SUCCESS);
}
Beispiel #21
0
int
main(int argc, char **argv)
{
	int					i, maxi, maxfd, listenfd, connfd, sockfd;
	int					nready, client[FD_SETSIZE];
	ssize_t				n;
	fd_set				rset, allset;
	char				line[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(7);

	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;
		nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(listenfd, &rset)) {	/* new client connection */
			printf("listening socket readable\n");
			sleep(5);
			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 = Readline(sockfd, line, MAXLINE)) == 0) {
						 /* connection closed by client */
					Close(sockfd);
					FD_CLR(sockfd, &allset);
					client[i] = -1;
				}
				Writen(sockfd, line, n);

				if (--nready <= 0)
					break;				/* no more readable descriptors */
			}
		}
	}
}
Beispiel #22
0
void
str_clib(FILE *fp, int sockfd, int pfd)
{
	int n;
	char buf[MAXLINE];

	int maxfdp1,stdineof;
	fd_set rset;

	stdineof=0;
	FD_ZERO(&rset);

	for( ; ; )
	{
		if(stdineof==0)
			FD_SET(fileno(fp),&rset);

		FD_SET(sockfd,&rset);	

		maxfdp1=max(fileno(fp),sockfd)+1;
		Select(maxfdp1,&rset,NULL,NULL,NULL);	

		if(FD_ISSET(sockfd,&rset))
		{
			if((n=Readline(sockfd, buf, MAXLINE))==0)
			{
				if(stdineof==1)
				{
					sprintf(buf,"%s","Normal Exit!\n");
					Writen(pfd,buf,strlen(buf));
					close(pfd);
					return;
				}
				else
				{
					sprintf(buf,"%s","Server Terminated Prematurely!\n");
					Writen(pfd,buf,strlen(buf));
					close(pfd);
					return;
				}
			}
			Write(fileno(stdout),buf,n);
			Writen(pfd,buf,strlen(buf)+1);
		}
		if(FD_ISSET(fileno(fp),&rset))
		{
			if((n=Read(fileno(fp),buf,MAXLINE))==0)
			{
				stdineof=1;
				Shutdown(sockfd,SHUT_WR);
				FD_CLR(fileno(fp),&rset);
				continue;
			}
			Writen(sockfd,buf,n);
		}

		/*
		while( (n=read(sockfd, recvline, MAXLINE)) > 0 )
		{
			recvline[n]=0;
			if(fputs(recvline, stdout) == EOF)
				err_sys("fputs error\n");	
			write(pfd,recvline,strlen(recvline)+1);
		}

		if(n<0)
			err_sys("read error\n");*/
	}

	exit(0);
}