title: Setting a timeout when using connect() in C++
body: <p>I'm using sockets in c++ on linux to connect to a server using connect(), but it doesn't seem to have a timeout value.  What would be the easiest/best way to give it a timeout of a few seconds.  I'll post the code I have up to, and including, the blocking call to connect():</p>
  
  <pre><code>using namespace std;
  int main( int argc, char* argv[] )
  {
    // Interpret the command line arguments
    string uri_string = "";
  
    if ( argc != 2 )
    {
      cerr &lt;&lt; "Usage: " &lt;&lt; argv[0];
      cerr &lt;&lt; " &lt;URI&gt;" &lt;&lt; endl;
      return 1;
    }
    else
    {
      uri_string = argv[1];
    }
  
    // Create URI object and have it parse the uri_string
    URI *uri = URI::Parse(uri_string);
  
    if ( uri == NULL )
    {
      cerr &lt;&lt; "Error: Cannot parse URI." &lt;&lt; endl;
      return 2;
    }
  
    // Check the port number specified, if none use port 80
    unsigned port = 80;
    if ( uri-&gt;Is_port_defined() )
    {
      port = uri-&gt;Get_port();
    }
  
    // Create TCP socket and connect to server
    int tcp_sock = socket( AF_INET, SOCK_STREAM, 0 );
    if ( tcp_sock &lt; 0 )
    {
      cerr &lt;&lt; "Unable to create TCP socket." &lt;&lt; endl;
      return 3;
    }
  
    sockaddr_in server;
    socklen_t slen = sizeof(server);
  
    server.sin_family = AF_INET;
    server.sin_port = htons( port );
    cout &lt;&lt; "Resolving " &lt;&lt; uri-&gt;Get_host() &lt;&lt; "... ";
    hostent *hostp = gethostbyname( uri-&gt;Get_host().c_str() );
    memcpy( &amp;server.sin_addr, hostp-&gt;h_addr, hostp-&gt;h_length );
  
    struct in_addr **pptr;
    pptr = (struct in_addr **)hostp-&gt;h_addr_list;
  
    string ip_addr = "";
    while( *pptr != NULL ) {
      ip_addr += inet_ntoa(**(pptr++));
    }
    cout &lt;&lt; ip_addr &lt;&lt; endl;
  
    cout &lt;&lt; "Connecting to " &lt;&lt; uri-&gt;Get_host() &lt;&lt; "|" &lt;&lt; ip_addr &lt;&lt; "|:";
    cout &lt;&lt; port &lt;&lt; "... ";
    if ( connect( tcp_sock, (sockaddr*)&amp;server, slen ) &lt; 0 )
    {
      cerr &lt;&lt; "Unable to connect to server via TCP." &lt;&lt; endl;
      close( tcp_sock );
      return 4;
    }
    cout &lt;&lt; "connected." &lt;&lt; endl;
  
    // rest of code
  }
  </code></pre>