Entry
How can I free a port that has been used by a python server?
Sep 13th, 2000 15:17
Tomas V.V.Cox, unknown unknown, Johannes Stezenbach
Problem:
######################################################################
class Server (SocketServer.ThreadingMixIn,
BaseHTTPServer.HTTPServer):
pass
if __name__ == '__main__':
port = 1729 # Called from interactive session, debug mode.
proxy = Server (('127.0.0.1', port), Handler)
proxy.serve_forever ()
######################################################################
The problem is, when I run this more than once in interactive mode, I
get the error:
socket.error: (98, 'Address already in use')
Is there some way to free up port 1729 when proxy gets destroyed?
Solution:
Normally you should close the socket properly before exiting. You could
try to catch KeyboardInterrupt or whatever signal you use to break out
of serve_forever(), but it's problematic with multithreaded servers.
Workaround:
-----
class Server (SocketServer.ThreadingMixIn,
BaseHTTPServer.HTTPServer):
def server_bind(self):
import socket
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
BaseHTTPServer.HTTPServer.server_bind(self)
-----
Note that this doesn't free up the port, instead it allows more than
one process to bind to it, under certain circumstances (bind() still
fails if there's already a socket actively listening on that port).
See socket(7) (Linux) for details.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An other thing you can do is wait (between 5 and 30 seconds) :)
Tomas V.V.Cox