/* server2.c -- request-reply demo Compilation on cs: gcc -Wall -o server2 server2.c -lnsl -lsocket -lresolv */ #include #include #include #include #include #include #include #include #include #include #include #define BMAX 100 #define BACKLOG 5 // how many pending connections queue will hold #define MESS "Hello, world!\015\012" int main(int argc, char *argv[]) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information int sin_size, count, i, numbytes; int port = 5555; // default port char yes='1'; char buf[BMAX+1]; if (argc > 1) port = atoi(argv[1]); /* get & set up socket */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } /* construct local address struct */ my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(port); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct /* bind to the port */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } /* open port for connections */ if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { // main accept() loop sin_size = sizeof(struct sockaddr_in); /* accept new connection */ if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr)); /* receive request */ if ((numbytes=recv(new_fd, buf, BMAX, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; /* terminate string */ count = atoi(buf); /* convert to int */ /* send count messages (lines) */ printf("%d\n", count); for (i = 0; i < count; i++) { if (send(new_fd, MESS, strlen(MESS), 0) == -1) { /* you should also check for incomplete sends */ perror("send"); break; } } close(new_fd); /* close socket of one connection */ } return 0; }