echod_poll.c

#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 <poll.h>

#include <errno.h>

#define ECHO_PORT 7
#define MAX_BACKLOG 5
#define RCVBUFSIZE 256
#define MAX_NFDS 1024
#define POLL_TIMEOUT 1000

#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(): %d.\n", sock);

  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;
  }

  return len;
}

int main() {
  int sock;
  struct sockaddr_in addr;
  int sockets[MAX_NFDS];

  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)");
  }

  memset(sockets, 0, sizeof(sockets));
  sockets[sock] = 1;

  while (1) {
    int i, nfds = 0;
    struct sockaddr_in sa;
    socklen_t len = sizeof(sa);
    struct pollfd pollfds[MAX_NFDS];

    for (i = 0; i < MAX_NFDS; i++) {
      if (sockets[i]) {
        pollfds[nfds].fd = i;
        pollfds[nfds].events = POLLIN;
        nfds++;
      }
    }

    if (poll(pollfds, nfds, POLL_TIMEOUT) < 0) {
      die_with_err("poll(2)");
    }

    for (i = 0; i < nfds; i++) {
      int fd = pollfds[i].fd;

      if (!(pollfds[i].revents & POLLIN)) { continue; }

      if (sock == fd) {
        int s;

        if ((s = accept(sock, (struct sockaddr*) &sa, &len)) < 0) {
          if (EINTR == errno) { continue; }
          die_with_err("accept(2)");
        }

        debug("accepted.\n");
        sockets[s] = 1;
      } else {
        if (echo(fd) < 1) {
          sockets[fd] = 0;
        }
      }
    }
  }

  close(sock);
}