title: Using C sockets: Address already in use
body: <p>So the basic premise of my program is that I'm supposed to create a tcp session, direct traffic through it, and detect any connection losses. If the connection does break, I need to close the sockets and reopen them (using the same ports) in such a way that it will seem like the connection (almost) never died. It should also be noted that the two programs will be treated as proxies (data gets sent to them, if the connection breaks it gets stored until connection is fixed, then data is sent off).</p>
  
  <p>I've done some research and gone ahead and used setsockopt() with the SO_REUSEADDR option to set the socket options so that I can reuse the address.</p>
  
  <p>Here's the basic algorithm I do to detect a connection break using signals: </p>
  
  <ol>
  <li>After initial setup of sockets, begin sending data</li>
  <li>After x seconds, set a flag to false, which will prevent all other data from being sent</li>
  <li>Send a single piece of data to let the other program know the connection is still open, reset timer to x seconds</li>
  <li>If I receive same piece of data from the program, set the flag to true to continue sending</li>
  <li>If I don't receive the data after x seconds, close the socket and attempt to reconnect</li>
  </ol>
  
  <p>(step 5 is where I'm getting the error).</p>
  
  <p>Essentially one program is a client(on one VM) and one program is a server(on another VM), each sending and receiving data to/from each other and to/from another program on each VM.</p>
  
  <p>My question is: Given that I'm still getting this error after setting the socket options, why am I not allowed to re-bind the address when a connection has been detected?</p>
  
  <p>The server is the one complaining when a disconnect is detected (I close the socket, open a new one, set the option, and attempt to bind the port with the same information).</p>
  
  <p>One other thing of note is the way I'm receiving the data from the sockets. If I have a socket open, I'm basically reading it by doing the following:</p>
  
  <pre><code>while((x = recv(socket, buff, 1, 0)&gt;=0){
  
      //add to buffer
      // send out to other program if connection is alive
  }
  </code></pre>
  
  <p>Since I'm using the timer to close/reopen the socket, and this is in a different thread, will this prevent the socket from closing?</p>