title: C unix socket programming, connect() hanging on invalid host name
body: <p>I'm having a hanging issue with the <code>connect</code> function when I pass an invalid host name. </p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define ERROR_NUM           -1
  #define BUFFER_SIZE         500
  #define HOST_NAME_SIZE      255
  #define MY_ID       5
  
  int  main(int argc, char* argv[])
  {
  int hSocket;                 /* handle to socket */
  struct hostent* pHostInfo;   /* holds info about a machine */
  struct sockaddr_in Address;  /* Internet socket address stuct */
  long nHostAddress;
  char pBuffer[BUFFER_SIZE];
  char userName[BUFFER_SIZE];
  char hostName[HOST_NAME_SIZE];
  
  if(argc &lt; 2){
      printf("\nUsage: username@hostname\n");
      return 0;
  }
  else{
      int i = 0;
      int length;
      if((length = strlen(argv[1])) &gt;= BUFFER_SIZE){
          printf("Argument entered is too long\n");
          return 0;
      }
      while(*(argv[1] + i) != '@'){
          ++i;
          if(i &gt;= length){
              printf("Usage: username@hostname\n");
              return 0;
          }
      }
      strncpy(userName, argv[1], i);
      argv[1]+=(i+1);
      strcpy(hostName,argv[1]);
  }
  
  printf("\nMaking a socket\n");
  if((hSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == ERROR_NUM){
      printf("\nCould not make a socket\n");
      return 0;
  }
  
  /* get IP address from name */
  pHostInfo=gethostbyname(hostName);
  if(!pHostInfo){
      printf("Could not resolve host name\n");
      return 0;
  }
  /* copy address into long */
  memset(&amp;nHostAddress, 0, sizeof(nHostAddress));
  memcpy(&amp;nHostAddress,pHostInfo-&gt;h_addr,pHostInfo-&gt;h_length);
  
  /* fill address struct */
  Address.sin_addr.s_addr=nHostAddress;
  Address.sin_family=AF_INET;
  /* finding host port num */
  int x = 5000 + (MY_ID-1)* 10;
  int y = 5000 + (MY_ID*10) - 1;
  for(x; x &lt;= y; ++x){
      Address.sin_port=htons(x);
      if(connect(hSocket,(struct sockaddr*)&amp;Address,sizeof(Address)) &gt; ERROR_NUM){
          break;
      }
  }
  if(x &gt; y){
      printf("\nFailed to connect to host port\n");
      return 0;
  }
  printf("\nConnected to %s on port %d\n", hostName, x);
  printf("Client closing socket\n\n");                    
  if(close(hSocket) == ERROR_NUM){
      printf("\nCould not close socket\n");
      return 0;
  }
  </code></pre>
  
  <p><code>connect()</code> is hanging if I give an invalid host name as an argument.  If I give a valid host name everything works according to plan.  A valid host name but invalid port will go to return 0.  My question is, why is it hanging and not returning -1 when I give an invalid host name? </p>
  
  <p>Thanks for any help</p>