title: bad file descriptor with close() socket (c++)
body: <p>I'm running out of file descriptors when my program can't connect another host. The close() system call doesn't work, the number of open sockets increases. I can se it with</p>
  <blockquote>
  <p>cat /proc/sys/fs/file-nr</p>
  </blockquote>
  <p>Print from console:</p>
  <blockquote>
  <p>connect: No route to host</p>
  <p>close: Bad file descriptor</p>
  <p>connect: No route to host</p>
  <p>close: Bad file descriptor</p>
  <p>..</p>
  </blockquote>
  <p>Code:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.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;iostream&gt;
  using namespace std;
  
  #define PORT            1238
  #define MESSAGE         &quot;Yow!!! Are we having fun yet?!?&quot;
  #define SERVERHOST      &quot;192.168.9.101&quot;
  
  void
  write_to_server (int filedes)
  {
    int nbytes;
  
    nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
    if (nbytes &lt; 0)
      {
        perror (&quot;write&quot;);
      }
  }
  
  void
  init_sockaddr (struct sockaddr_in *name,
                 const char *hostname,
                 uint16_t port)
  {
    struct hostent *hostinfo;
  
    name-&gt;sin_family = AF_INET;
    name-&gt;sin_port = htons (port);
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL)
      {
        fprintf (stderr, &quot;Unknown host %s.\n&quot;, hostname);
      }
    name-&gt;sin_addr = *(struct in_addr *) hostinfo-&gt;h_addr;
  }
  
  int main() 
  {
   for (;;)
   {
    sleep(1);
    int sock;
    struct sockaddr_in servername;
  
    /* Create the socket. */
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock &lt; 0)
    {
     perror (&quot;socket (client)&quot;);
    }
  
    /* Connect to the server. */
    init_sockaddr (&amp;servername, SERVERHOST, PORT);
    if (0 &gt; connect (sock,
      (struct sockaddr *) &amp;servername,
      sizeof (servername)))
    {
     perror (&quot;connect&quot;);
     sock = -1;
    }
  
    /* Send data to the server. */
    if (sock &gt; -1)
     write_to_server (sock);
    if (close (sock) != 0)
     perror(&quot;close&quot;);
   }
  return 0;
  }
  </code></pre>
  <p>Fix:</p>
  <pre><code>  if (0 &gt; connect (sock,
      (struct sockaddr *) &amp;servername,
      sizeof (servername)))
    {
     perror (&quot;connect&quot;);
    }
  
    else
     write_to_server (sock);
  
    if (close (sock) != 0)
     perror(&quot;close&quot;);
  </code></pre>