#include #include #include #include #include #include #include #include #define PORT 1200 #define MAXMSGLENGTH 12 int main (void) { int sock; /* server socket, which accepts new connections */ fd_set active_fd_set, read_fd_set; /* sets of serving socket descriptors */ int i; struct sockaddr_in clientname, server; size_t size; /* Create the socket and set it up to accept connections */ sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("socket"); exit(EXIT_FAILURE); } /* Give the socket a name */ server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (struct sockaddr *) &server, sizeof(server)) < 0) { perror("bind"); exit(EXIT_FAILURE); } if (listen(sock, 10) < 0) { perror("listen"); exit(EXIT_FAILURE); } /* Initialize the set of active sockets */ FD_ZERO (&active_fd_set); FD_SET (sock, &active_fd_set); /* going into server main loop */ while (1) { /* Block until unput arrives on one or more active sockets */ read_fd_set = active_fd_set; if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) { perror ("select"); exit (EXIT_FAILURE); } /* Service all sockets with input pending */ for (i = 0; i < FD_SETSIZE; ++i) { if (i == sock) { /* Connection on server socket - new connection request */ int new; size = sizeof (clientname); new = accept(sock, (struct sockaddr *) &clientname, &size); if (new < 0) { perror ("accept"); exit (EXIT_FAILURE); } fprintf (stderr, "connect from host %s, port %hd.\n", inet_ntoa (clientname.sin_addr), ntohs(clientname.sin_port)); FD_SET (new, &active_fd_set); } else { if (read_from_client (i) < 0) { close (i); FD_CLR (i, &active_fd_set); } } } } } int read_from_client (int fd) { char buffer[MAXMSGLENGTH]; int nbytes; nbytes = read (fd, buffer, MAXMSGLENGTH); if (nbytes < 0) { perror("read"); exit(EXIT_FAILURE); } else if (nbytes == 0) { return -1; } else { fprintf (stderr, "got message from %d client: `%s'\n", fd, buffer); return 0; } }