#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define SERVER_PORT 5432
#define MAX_PENDING  5
#define MAX_LINE     256

int main()
{
  /* I. Declare variables. */
  struct sockaddr_in sin;
  char buf[MAX_LINE];
  int len;
  int s;
  int new_s;

  /* II. Build address data structure. */
  bzero((char *)&sin, sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;
  sin.sin_port = htons(SERVER_PORT);

  /* III. Set up passive open. */
  if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    perror("server: trouble creating socket.");
    exit(1);
  }
  if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0) {
    perror("server: trouble binding socket");
    exit(2);
  }
  listen(s, MAX_PENDING);

  /* IV. Wait for connections. */
  while (1) {
    if ((new_s = accept(s, (struct sockaddr *)&sin, &len)) < 0) {
      perror("server: trouble accepting connection");
      exit(3);
    }
    /* V. Print everything you read from the socket. */
    printf("------- STARTED -----------\n");
    while (len = recv(new_s, buf, sizeof(buf), 0))
      fputs(buf, stdout);
    printf("------- FINISHED ----------\n");
    close(new_s);
  } /* while (1) */
} /* main */
