title: C socket: Connection refused[Errno 111]
body: <p>I'm writing a simple socket server/client. Here is the <strong>server</strong> part:  </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;string.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;time.h&gt;
  
  using namespace std;
  
  int main() {
  int listenfd;
  int connfd;
  sockaddr_in servaddr;
  char buf[100];
  time_t ticks;
  
  if(listenfd = socket(AF_INET,SOCK_STREAM,0) &lt; 0)
      cout &lt;&lt; "listenfd" &lt;&lt; endl;
  bzero(&amp;servaddr,sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(10000);
  
  bind(listenfd,(const struct sockaddr*)&amp;servaddr,sizeof(servaddr));
  
  listen(listenfd,5);
  
  for(;;) {
      connfd = accept(listenfd,(struct sockaddr *)NULL,NULL);
      //cout &lt;&lt; "accept link" &lt;&lt; endl;
      ticks = time(NULL);
      snprintf(buf,sizeof(buf),"%.24s\r\n",ctime(&amp;ticks));
      //cout &lt;&lt; buf &lt;&lt; endl;
      write(connfd,buf,strlen(buf));
      close(connfd);
  }
  }
  </code></pre>
  
  <p>And here is the <strong>client</strong> part:  </p>
  
  <pre><code>#include &lt;netinet/in.h&gt;
  #include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;arpa/inet.h&gt;
  using namespace std;
  #define MAX 100
  int main(int argc,char **argv) {
      int socketfd;
      int n;
      char buf[MAX+1];
      sockaddr_in servaddr;
  
      if(argc !=2 )
          cout &lt;&lt; "stdin error " &lt;&lt; endl;
  
      if((socketfd = socket(AF_INET,SOCK_STREAM,0)) &lt; 0)
           cout &lt;&lt; " socekt error " &lt;&lt; endl;
       bzero(&amp;servaddr,sizeof(servaddr));
       servaddr.sin_family = AF_INET;
       servaddr.sin_port = htons(10000);
       if(inet_pton(AF_INET,argv[1],&amp;servaddr.sin_addr) &lt;= 0)
           cout &lt;&lt; "inet_pton error" &lt;&lt; endl;
       cout &lt;&lt; "prepare linking" &lt;&lt; endl;
       if(connect(socketfd,(const struct sockaddr*)&amp;servaddr,sizeof(struct sockaddr)) &lt; 0)
       {
           cout &lt;&lt; " connet error" &lt;&lt; endl;
           cout &lt;&lt; strerror(errno);
       }
       while((n = read(socketfd,buf,MAX)) &gt;0) {
           buf[n] = 0;
           if(fputs(buf,stdout) == EOF)
               cout &lt;&lt; "cout error" &lt;&lt; endl;
       }
       if(n &lt; 0)
            cout &lt;&lt; "read error" &lt;&lt; endl;
       exit(0);
  }
  </code></pre>
  
  <p>I start the server first and run the client like: <code>./client 127.0.0.1</code>, but connection failed with errno 111. </p>
  
  <p>I'm using Ubuntu 12.04 system.</p>