title: Understanding a Select loop for receiving UDP messages and opening TCP sockets
body: <p>Hi I'm working a project for a networking class where we are creating nodes in a network that receive messages from a control app via udp and then create tcp connections with other nodes. The basic order goes: 1) control manager sends udp message to node A telling it to connnect to node B 2) node A receives udp message and forwards the udp message to node B 3) node B receives the udp message, randomly choses a port number, opens a listening tcp socket on that port, and sends a udp message back to A with the port number 4) node A receives the udp message and opens a connection on that tcp port to node B.</p>
  
  <p>Basically, I want to loop on udp messages received and jump to my message parsing function while at the same time, looping for tcp connections. That part seems simple enough but I don't really understand how to add listening sockets to the file descriptor list. The following code is what i put together and im wondering if the basic structure looks correct? I don't really understand how to create listening tcp socket and add it to the fd list?</p>
  
  <pre><code>SOCKET udpsock;
  udpsock = initudp(port); //setup udp socket
  SOCKET tcpsock;
  FD_ZERO(&amp;rdsocks);
  
  max = udpsock + 1;
  while(1)
  {
      SOCKET temp;
  
      FD_SET(udpsock,&amp;rdsocks);//setup udp macros
      FD_SET(tcpsock,&amp;rdsocks);
  
      if( select(max,&amp;rdsocks,NULL,NULL,NULL) == SOCKET_ERROR )
      {
          perror("Select error");
          WSACleanup();
          return 1;
      }
      for(temp = 0; temp&lt;=max;temp++) // loop on TCP sockets
      {
          if(FD_ISSET(temp,&amp;rdsocks))
          {
              printf("Socket %d is ready \n",temp);
              // process tcp messages
          }
  
      }
      if(FD_ISSET(udpsock,&amp;rdsocks)) // udp connection, parse control message
      {
          int ret = 0;
          res = recvfrom(udpsock, buff,sizeof(buff),0,(struct sockaddr*)&amp;udpclient,lenaddr);
          //process udp message, setup tcp connection here if requested and add to file descriptor list?
      }
  
  }
  </code></pre>