#include #include #include #include #include #include #include #include "server.h" // // parseArguments // // Returns the first command-line argument of the program, converted // to an integer. If there is not exactly one command-line argument, // or if the argument does not represent an integer, then it prints // an error message and exits the program. // int parseArguments(int argc, char **argv) { if(argc != 2 || strcmp(argv[1], "") == 0) { fprintf(stderr, "usage: %s #\n", argv[0]); exit(-1); } int ret = atoi(argv[1]); if(ret <= 0) { fprintf(stderr, "usage: %s #\n", argv[0]); exit(-1); } return ret; } // // getServerSocket // // Opens a server socket bound to port !portnum!, returning the // file descriptor of the socket. If any errors are encountered, // the function prints a function and exits the program. // int getServerSocket(int portnum) { struct hostent *hp; int sock; int err; struct sockaddr_in sa; // see who I am /* gethostname(myname, MAXHOSTNAMELEN); hp = gethostbyname(myname); if(hp == NULL) { perror("gethostname"); exit(-1); } */ // create a Internet socket with which to work sock = socket(PF_INET, SOCK_STREAM, 0); if(sock == -1) { perror("socket"); exit(-1); } // initialize the socket's port number memset(&sa, 0, sizeof(struct sockaddr_in)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons((unsigned short) portnum); err = bind(sock, (struct sockaddr*) &sa, sizeof(struct sockaddr_in)); if(err < 0) { perror("bind"); exit(-1); } // set up socket as a listener (willing to queue up to five // connection requests) err = listen(sock, 5); if(err < 0) { perror("listen"); exit(-1); } return sock; } // // splitLine // // Breaks the string to which !buf! points into a sequence of // words. The pointer to each successive word is placed into // the !argv! array, stopping at !max_args! words. The function // returns the number of words found in !buf! (up to !max_args!). // int splitLine(char *buf, char **argv, int max_args) { int arg; while(isspace(*buf)) ++buf; // skip over initial spaces for(arg = 0; arg < max_args && *buf != '\0'; arg++) { argv[arg] = buf; // save word in array while(*buf != '\0' && !isspace(*buf)) ++buf; // skip past word if(*buf != '\0') { // if spaces follow word: *buf = '\0'; // replace space with NUL do ++buf; while(isspace(*buf)); // skip following spaces } } return arg; // the array has been filled with words }