
// simple TCP server listening on *:1234
// it sends "hello client" to every client that connects, and closes the
// connection

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <err.h>
#include <stdio.h>
#include <unistd.h>

#define BUFFS 1024

int main ()
{
   int ret, fd, fd2;
   unsigned len;
   struct sockaddr_in addr;
   char buff[BUFFS];

   // create a socket
   fd = socket (AF_INET, SOCK_STREAM, 0);
   if (fd == -1) err (1, "socket");

   addr.sin_family = AF_INET;
   addr.sin_port = htons (1234);
   addr.sin_addr.s_addr = INADDR_ANY;

   // accept connections from all interfaces, port 1234
   ret = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
   if (ret == -1) err (1, "bind");

   // start listening, using an accept queue of 10 clients
   ret = listen (fd, 10);
   if (ret == -1) err (1, "listen");

   printf ("Listening on all interfaces, port 1234.\n");
   printf ("Type Ctrl+c to terminate...\n\n");

   while (1)
   {
      len = sizeof (struct sockaddr_in);
      fd2 = accept (fd, (struct sockaddr *) &addr, &len);
      if (fd2 == -1) err (1, "accept");

      inet_ntop (AF_INET, &addr.sin_addr, buff, BUFFS);
      printf ("Accepted client %s:%d, fd2 %d\n", buff, ntohs (addr.sin_port), fd2);

      ret = write (fd2, "hello client, I'm closing your connection!\n", 43);
      if (ret == -1) err (1, "write");
      close (fd2);
      printf ("Wrote welcome message and closed connection.\n\n");
   }
}

