#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <unistd.h> #include <sys/select.h> #include <sys/time.h> #include <errno.h> #define ECHO_PORT 7 #define MAX_BACKLOG 5 #define RCVBUFSIZE 256 #define die(s) do { fprintf(stderr, "%s\n", (s)); exit(1); } while(0) #define die_with_err(s) do { perror((s)); exit(1); } while(0) #ifdef DEBUG #define debug(...) do { fprintf(stderr, __VA_ARGS__); } while(0) #else #define debug(...) do {} while(0) #endif int echo(int sock) { char buf[RCVBUFSIZE + 1]; size_t len; debug("echo() bgein.\n"); if ((len = recv(sock, buf, RCVBUFSIZE, 0)) < 0) { perror("recv(2)"); close(sock); return -1; } if (len == 0) { close(sock); return 0; } buf[len] = '\0'; debug("recv: %s.\n", buf); if (send(sock, buf, len, 0) < 0) { perror("send(2)"); close(sock); return -1; } debug("echo() end.\n"); return len; } int main() { int sock; struct sockaddr_in addr; fd_set fds; if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { die_with_err("socket(2)"); } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(ECHO_PORT); if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) < 0) { die_with_err("bind(2)"); } if (listen(sock, MAX_BACKLOG) < 0) { die_with_err("listen(2)"); } FD_ZERO(&fds); FD_SET(sock, &fds); while (1) { int i, s; struct sockaddr_in sa; socklen_t len = sizeof(sa); fd_set _fds; struct timeval timeout; timeout.tv_sec = 1; timeout.tv_usec = 0; memcpy(&_fds, &fds, sizeof(fd_set)); if (select(FD_SETSIZE, &_fds, NULL, NULL, &timeout) < 0) { die_with_err("select(2)"); } for (i = 0; i < FD_SETSIZE; i++) { if (!FD_ISSET(i, &_fds)) { continue; } if (sock == i) { if ((s = accept(sock, (struct sockaddr*) &sa, &len)) < 0) { if (EINTR == errno) { continue; } die_with_err("accept(2)"); } debug("accepted.\n"); FD_SET(s, &fds); } else { if (echo(i) < 1) { FD_CLR(i, &fds); } } } } close(sock); }