
/*
 * Opens 2 TCP connexions to localhost:1234 and localhost:1235 and writes the
 * received data to stdout.
 *
 * You can test this code using two instances of netcat(1) on two different
 * terminals:
 *
 * nc -l 1234
 * nc -l 1235
 *
 * Writing on each of the terminals will trigger data to be received by this
 * program, and show in the screen
 */

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

#include <string.h>

#define BUFFS 1024

int main ()
{
   int ret, i, fd1, fd2, count;
   struct sockaddr_in addr;
   char buff[BUFFS];
   struct pollfd pfds[2];

   // create two sockets
   fd1 = socket (AF_INET, SOCK_STREAM, 0);
   if (fd1 == -1) err (1, "socket: fd1");

   fd2 = socket (AF_INET, SOCK_STREAM, 0);
   if (fd2 == -1) err (1, "socket: fd2");

   // connect fd1 to 127.0.0.1, port 1234
   addr.sin_family = AF_INET;
   addr.sin_port = htons (1234);
   addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
   ret = connect (fd1, (struct sockaddr *) &addr, sizeof (addr));
   if (ret == -1) err (1, "connect: fd1");
   printf ("Socket 1 connected to localhost:1234!\n");

   // connect fd2 to 127.0.0.1, port 1234
   addr.sin_port = htons (1235);
   ret = connect (fd2, (struct sockaddr *) &addr, sizeof (addr));
   if (ret == -1) err (1, "connect: fd2");
   printf ("Socket 2 connected to localhost:1235!\n");

   // fill the data structure for poll: we are interested in reading the
   // descriptors
   pfds[0].fd = fd1;
   pfds[0].events = POLLIN;

   pfds[1].fd = fd2;
   pfds[1].events = POLLIN;

   count = 2;

   while (1)
   {
      // wait for data to arrive on at least 1 connection
      ret = poll (pfds, 2, -1);
      if (ret == -1) err (1, "poll");

      for (i = 0; i < 2; i++)
      {
         // read this fd only if there is data waiting
         if (! (pfds[i].revents & POLLIN)) continue;

         // read data and show it on stdout
         ret = read (pfds[i].fd, buff, BUFFS);
         if (ret == -1) err (1, "read");
         printf ("i %d, read %d bytes, '%.*s'\n", i, ret, ret, buff);

         // if EOF, close connection, disable notifications, and check if
         // both connections are already closed
         if (ret == 0)
         {
            printf ("i %d, closing!", i);
            close (pfds[i].fd);
            pfds[i].fd = -1;
            count--;
            continue;
         }
      }

      // if both connections closed, terminate
      if (count == 0) break;
   }

   return 0;
}
