/*************************************************************************** tcp_server.c Designed as a simple class example. The program waits for a request. It assumes that request is numerical. It adds +1 to the input and sends it back. This program expects no arguments: tcp_server Version 1.0 Ocotber, 2002 Yvan Petillot. ****************************************************************************/ #include #include #include #define TRUE 1 #define FALSE 0 #define BUFFER_SIZE 100 #define PORT 10000 void SysError( char * ); /* Main Program */ main ( int argc, char *argv[] ) { long input_value; int family = AF_INET; /* The default for most cases */ int type = SOCK_STREAM; /* Says it's a TCP connection */ in_port_t port = PORT; /* Use a free port to establish connection */ int result; struct sockaddr_in server; /* Structure storing socket info */ struct sockaddr_in client; /* Structure storing socket info */ int lsa = sizeof(server); int fdListen, fdConn, fd; /* Socket id. On Unix a socket is a file descriptor */ char console_buffer[BUFFER_SIZE]; char ip_input_buffer[BUFFER_SIZE]; char ip_output_buffer[BUFFER_SIZE]; /* Create socket*/ if ((fd = socket (family, type, 0)) < 0) { SysError ("Error on socket"); } /* Fills sa socket structure with correct fields */ server.sin_family = family; server.sin_port = port; /* port*/ server.sin_addr.s_addr = htonl(INADDR_ANY); /* the kernel assigns the IP addr*/ /* Server code */ /* First bind fd and sa structure*/ if (bind (fd, (struct sockaddr *)&server, lsa ) == -1) SysError ("Error on bind"); /* Now listen for a client to connect */ if (listen (fd, SOMAXCONN) == -1) /* set up for listening */ SysError ("Error on listen"); fdListen = fd; /* Infinite loop until fault */ while( TRUE ) { /* Wait for a client and do accept */ if ((fdConn = accept (fdListen, (struct sockaddr *)&client, &lsa )) <0) SysError ("Error on accept"); printf("Got Connection from %s\n",inet_ntoa(client.sin_addr)); /* After Accept Create Son and handle connection */ if (!fork()) { /* Fd not needed in child */ close(fd); /*Make sure inout buffer is void */ bzero( ip_input_buffer, sizeof( ip_input_buffer )); /* While client is sending info This is blocking*/ while ( recv( fdConn, ip_input_buffer, BUFFER_SIZE - 2, 0 ) > 0 ) { /* Old version */ /* Get Value input_value = atoi( ip_input_buffer ); /* Increment value by one input_value = input_value + 1;*/ /* Make sure output buffer is empty */ bzero( ip_output_buffer, sizeof( ip_output_buffer )); /* Put output value in output buffer */ strcpy(ip_output_buffer,ip_input_buffer); //sprintf( ip_output_buffer, "%d", input_value ); /* Send value back to client */ if ( send( fdConn, ip_output_buffer, strlen(ip_output_buffer) +1, 0) <= 0 ) SysError( "Error on send" ); } }/* End of while recv is successful */ close (fdConn); } /* End of while TRUE */ } /* End of server case */ void SysError( char *string ) { printf( "Error found: String given is --> %s\n", string ); exit(0); }