title: C: socket connection timeout
body: <p>I have a simple program to check if a port is open, but I want to shorten the timeout length on the socket connection because the default is far too long. I'm not sure how to do this though. Here's the code:</p>
  
  <pre><code>#include &lt;sys/socket.h&gt;
  #include &lt;sys/time.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char **argv) {
      u_short port;                /* user specified port number */
      char addr[1023];             /* will be a copy of the address entered by u */
      struct sockaddr_in address;  /* the libc network address data structure */
      short int sock = -1;         /* file descriptor for the network socket */
  
      if (argc != 3) {
          fprintf(stderr, "Usage %s &lt;port_num&gt; &lt;address&gt;", argv[0]);
          return EXIT_FAILURE;
      }
  
      address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */
      address.sin_port = htons(atoi(argv[2]));            /* translate int2port num */
  
      sock = socket(AF_INET, SOCK_STREAM, 0);
      if (connect(sock,(struct sockaddr *)&amp;address,sizeof(address)) == 0) {
          printf("%i is open\n", port);
      }  
      close(sock);
      return 0;
  }
  </code></pre>