title: socket timeout: It works, but why and how, mainly the select() function?
body: <p>Here is part of the code I'm using now.</p>
  
  <pre><code>fd_set fdset;
  struct timeval tv;
  int flags = fcntl(sockfd, F_GETFL);    
  fcntl(sockfd, F_SETFL, O_NONBLOCK);
  
  connect(sockfd,(struct sockaddr *)&amp;serv_addr,sizeof(serv_addr));
  
  FD_ZERO(&amp;fdset);
  FD_SET(sockfd, &amp;fdset);
  tv.tv_sec = 3;          
  tv.tv_usec = 0;
  
  if (select(sockfd + 1, NULL, &amp;fdset, NULL, &amp;tv) == 1)
  {
      int so_error;
      socklen_t len = sizeof so_error;
      getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &amp;so_error, &amp;len);
      if (so_error == 0) {
          cout &lt;&lt; " - CONNECTION ESTABLISHED\n";
      }
  } else
  {
      cout &lt;&lt; " - TIMEOUT\n";
      exit(-1);
  }
  </code></pre>
  
  <p>I don't clearly understand how the select() function works, here in pseudo code is what I really want to do,</p>
  
  <pre><code>    bool showOnce = true;
  
      connect(sockfd,(struct sockaddr *)&amp;serv_addr,sizeof(serv_addr)) 
      while(stillConnecting) /*Some kind of flag of connection status*/
      {
          if(showOnce)
          {
              showOnce = false;
              cout &lt;&lt; "Connecting";
          }
      }
  
      if(connected) /*Another possible flag if it exists*/
          return true;
      else
          return false;
  </code></pre>
  
  <p>Is there anyway to implement this pseudo code, do these flags exist?</p>
  
  <p>EDIT: Also why is sockfd+1 in the select function in the code above? Why is one added to it?</p>