title: c TCP socket connection refused for localhost
body: <p>I'm trying to make a client/server program in localhost but the client can not connect to the server and I do not know what I'm doing wrong.  </p>
  
  <p>I have tried to debug the program and all the parameters seem to be ok.The server does bind, connect, listen and accept.</p>
  
  <p>With the client code a get <code>connect: Invalid argument</code> error. Client (I'm calling the client from the console with <code>./client localhost</code>):</p>
  
  <pre><code>#include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;errno.h&gt;
  
  int main(int argc, char * argv[])
  {
      int cd;
      struct hostent *hp;
      struct sockaddr_in s_ain;
      unsigned char byte;
  
      hp = gethostbyname(argv[1]);
      bzero((char *)&amp;s_ain, sizeof(s_ain));
      s_ain.sin_family = AF_INET;
      memcpy(&amp;(s_ain.sin_addr),  hp-&gt;h_addr, hp-&gt;h_length);
      s_ain.sin_port = htons(1025);
  
      cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if( connect(cd, (struct sockaddr*) &amp;s_ain, sizeof(s_ain) == -1) ) {
          fprintf(stderr, "connect: %s\n", strerror(errno));
          return -1;
      }       
  
      printf("%s\n", "IT WORKS!");
      close(cd);
      return 0;
  }
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>#include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  
  int main(void)
  {
      int sd, cd;
      socklen_t size;     
      unsigned char byte;
      struct sockaddr_in s_ain, c_ain;    
  
      sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  
      bzero((char *)&amp;s_ain, sizeof(s_ain));
      s_ain.sin_family = AF_INET;s_ain.sin_family = AF_INET;
      s_ain.sin_addr.s_addr = INADDR_ANY;
      s_ain.sin_port = htons(1025);
  
      if(bind(sd, (struct sockaddr *)&amp;s_ain, sizeof(s_ain)) == -1) {
          fprintf(stderr, "%s\n", "err bind");
          return -1;
      }
  
      if(listen(sd, 5) == -1) {
          fprintf(stderr, "%s\n", "err listen");
          return -1;
      }
  
      while(1) {
          size = sizeof(c_ain);
          cd = accept(sd, (struct sockaddr *)&amp;c_ain, &amp;size);
          printf("%s\n", "IT WORKS !");
      }
  }
  </code></pre>