[ACCEPTED]-SocketServer.ThreadingTCPServer - Cannot bind to address after program restart-tcpserver

Accepted answer
Score: 18

The above solution didn't work for me but 1 this one did:

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
Score: 16

In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) may be called 4 from the TCPServer class when the allow_reuse_address option 3 is set. So I was able to solve it as follows:

httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler, False) # Do not automatically bind
httpd.allow_reuse_address = True # Prevent 'cannot bind to address' errors on restart
httpd.server_bind()     # Manually bind, to support allow_reuse_address
httpd.server_activate() # (see above comment)

Anyway, thought 2 this might be useful. The solution will 1 differ slightly in Python 3.0

More Related questions