title: SocketServer: getting rid of '[Errno 98] Address already in use'
body: <p>I've been looking at the documentation for <a href="http://docs.python.org/2/library/socketserver.html" rel="noreferrer"><code>SocketServer</code></a>. I copied the TCP server code from the documentation and it runs fine. However, I noticed that whenever I ctrl-c'ed out of the program in my terminal, and then tried to run it again, I would get the following error:</p>
  
  <pre><code>socket.error: [Errno 98] Address already in use
  </code></pre>
  
  <p>I looked into how to remedy the problem by reading <a href="https://stackoverflow.com/questions/337115/setting-time-wait-tcp">this</a> and <a href="https://stackoverflow.com/questions/4465959/python-errno-98-address-already-in-use">this</a>. I added the following line to my code to try to allow reuse of the address:</p>
  
  <pre><code>server.allow_reuse_address = True
  </code></pre>
  
  <p>I am still experiencing the same problem even with the above line added. I also added a <code>try</code> and <code>except</code> around my <code>server.serve_forever()</code> function, catching the KeyboardInterrupt exception and calling <code>server.shutdown()</code> and <code>server.socket.close()</code> in hopes that the address would be freed.</p>
  
  <p>Here is the full extent of my TCP server code (Note: I excluded the MyTCPHandler class):</p>
  
  <pre><code>if __name__ == "__main__":
      HOST, PORT = '', 9999
  
      # Create the server, binding to localhost on port 9999
      server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
      server.allow_reuse_address = True
  
      # Activate the server; this will keep running until you
      # interrupt the program with Ctrl-C
      try:
          server.serve_forever()
      except KeyboardInterrupt:
          server.shutdown()
          server.socket.close()
  </code></pre>
  
  <p>I am still getting the error running the code above and have to wait close to a minute until the address is finally freed. This is frustrating when I'm debugging and changing my code constantly.</p>
  
  <p>I'm running this code using Python 2.7.3 on a RaspberryPi running Raspbian "Wheezy" 7.0.</p>