How to free a port that has been used by a python server?

Johannes Stezenbach yawyi at gmx.de
Sat Jun 3 07:40:53 EDT 2000


Alex <cut_me_out at hotmail.com> wrote:
>
>######################################################################
>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?  

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
failes if there's already a socket actively listening on that port).
See socket(7) (Linux) for details.

Johannes




More information about the Python-list mailing list