/*************************************************************************** udplisten Designed as a simple class example. The program waits for a request and sends it back to sender. This program expects one argument: udplisten The argument says where the server is Version 1.0 October, 2002 Yvan Petillot ****************************************************************************/ #include #include #include #include #include #include #include #include #include #include #define TRUE 1 #define FALSE 0 #define BUFFER_SIZE 100 #define PORT1 10000 #define PORT2 10000 void SysError( char * ); /* Main Program */ main ( int argc, char *argv[] ) { int count; long input_value; int family = AF_INET; /* The default for most cases */ int type = SOCK_DGRAM; /* Says it's a UDP connection */ int result; struct sockaddr_in my_addr; /* Structure storing socket info */ struct sockaddr_in their_addr; /* Structure storing socket info */ int lsa = sizeof(my_addr); int 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]; struct hostent *host; int on; /* Checks first we have the correct number of arguments */ if ( argc < 2 ) { printf( "The program expects arguments\n" ); printf( "udp \n" ); exit(0); } if ((host = gethostbyname(argv[1])) == (struct hostent *)NULL) { SysError("Gethostbyname failed"); } /* Create socket*/ if ((fd = socket (family, type, 0)) < 0) { SysError ("Error on socket"); } /* Fills my_addr socket structure with correct fields */ my_addr.sin_family = family; my_addr.sin_port = PORT1; my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* the kernel assigns the IP addr*/ /* Fills their socket structure with correct fields */ their_addr.sin_family = family; their_addr.sin_port = PORT2; memcpy((char *)&their_addr.sin_addr, (char *)host->h_addr, host->h_length); on = 1; setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on)); /* First bind fd and sa structure*/ if (bind (fd, (struct sockaddr *)&my_addr, sizeof(my_addr) ) == -1) SysError ("Error on bind"); /* While client is sending info This is blocking*/ while (TRUE ) { bzero( ip_input_buffer, sizeof( ip_input_buffer )); count = recvfrom( fd, ip_input_buffer,sizeof(ip_input_buffer),0,&their_addr,sizeof(their_addr)); if (count ==0) break; /* Make sure output buffer is empty */ bzero( ip_output_buffer, sizeof( ip_output_buffer )); /* Put output value in output buffer */ printf("Received:%s\n",ip_input_buffer); strcpy(ip_output_buffer,ip_input_buffer); /* Send value back to client */ /*if ( sendto(fd, ip_output_buffer, strlen(ip_output_buffer), 0,&their_addr,sizeof(their_addr) ) <= 0 ) SysError( "Error on send" );*/ } /* End of while recv is successful */ close (fd); } /* End of main */ void SysError( char *string ) { printf( "Error found: String given is --> %s\n", string ); exit(0); }