/************************************************************** * connectionless server programming * * Function: echo server (not iterative) * * Reference: Richard Stevens, Unix Network Programming, 1998 * * Created by: Hairong Qi **************************************************************/ #include /* for standard I/O */ #include /* for read() and write() */ #include /* for bzero() */ #include /* for atoi() */ #include /* for accept() and connect() */ #include #include /* for perror() */ #include /* for htonl() */ #define LISTENQ 2 #define BSIZE 256 #define USAGE "./serverudp portno\n" /** ** output the error message and exit **/ void error(char *msg) { perror(msg); exit(1); } /** ** the main function **/ int main(int argc, char *argv[]) { int listenfd, connfd; /* socket file descriptor */ int portno; int clilen; char buffer[BSIZE]; struct sockaddr_in serv_addr, cli_addr; int n; /* check the correctness of command-line inputs */ if (argc < 2) error(USAGE); /* create a listening socket */ listenfd = socket(PF_INET, SOCK_DGRAM, 0); /** change SOCK_STREAM to SOCK_DGRAM **/ if (listenfd < 0) error("ERROR opening socket"); /* specify local address */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); portno = atoi(argv[1]); serv_addr.sin_port = htons(portno); /* bind the address to the listening socket */ if (bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); /************************************************************************** ** the following would be commented for connectionless service by UDP ** ** listen(listenfd, LISTENQ); clilen = sizeof(cli_addr); connfd = accept(listenfd, (struct sockaddr *) &cli_addr, &clilen); if (connfd < 0) error("ERROR on accept"); ** ** commented part ends here ** ***************************************************************************/ /* start to receive data */ bzero(buffer, BSIZE); /*************************************************************************** ** can't use read() to receive messages as no client socket ID is created ** ** n = read(connfd, buffer, BSIZE-1); ** ** instead, using recvfrom(). Pay attention to its usage ***************************************************************************/ clilen = sizeof(cli_addr); n = recvfrom(listenfd, buffer, BSIZE-1, 0, (struct sockadd *)&cli_addr, &clilen); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); fflush(stdout); /* start to reply to client */ /*************************************************************************** ** similarly, can't use write(), use sendto() instead ** n = write(connfd, "I got your message", 18); ** ***************************************************************************/ n = sendto(listenfd, "I got your message", 18, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr)); if (n < 0) error("ERROR writing to socket"); return 0; }