Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SocketServer.ThreadingTCPServer - Cannot bind to address after program restart

As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted:

socket.error: [Errno 98] Address already in use

In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server:

httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()

How can I fix this error message?

like image 931
Justin Ethier Avatar asked Feb 16 '10 16:02

Justin Ethier


2 Answers

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

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
   server.serve_forever()
like image 100
Lynn Avatar answered Nov 02 '22 01:11

Lynn


In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) may be called from the TCPServer class when the allow_reuse_address option 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)
httpd.serve_forever()

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

like image 42
Justin Ethier Avatar answered Nov 02 '22 02:11

Justin Ethier