title: setsockopt: Bad file descriptor in C++
body: <p>I have the famous error <em>"address already in use"</em> because I have no check for the bind function.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>memset(&amp;(this-&gt;serv_addr), 0, sizeof(this-&gt;serv_addr));
  this-&gt;serv_addr.sin_family = AF_INET;
  this-&gt;serv_addr.sin_port = htons(port);
  this-&gt;serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  int yes = 1;
  if (setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&amp;yes,sizeof(int)) == -1) {
      perror("setsockopt");
      exit(1);
  }
  </code></pre>
  
  <p>But running code I got this:
  <code>setsockopt: Bad file descriptor</code></p>
  
  <p>The code is right, from the guide Beejnet.
  But why I got the error?
  Maybe the position of the code is wrong?</p>
  
  <p>The first the that sock_fd is called is in the function w_socket:</p>
  
  <pre><code>int retv;
  retv = socket(AF_INET, SOCK_STREAM, 0);
  if(retv == -1)
  {
      std::string err_msg(strerror(errno));
      err_msg = "[socket] " + err_msg;
      throw err_msg;
  }
  else
  {
      int reuse_opt = 1;
  
      setsockopt(this-&gt;sock_fd, SOL_SOCKET, SO_REUSEADDR, &amp;reuse_opt, sizeof(int));
      return retv;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>By default there's the sesockopt but no check.
  I've tried but it doesn't work.</p>