socket.SO_REUSEADDR

Gordon McMillan gmcm at hypernet.com
Thu Apr 20 14:05:39 CEST 2000


Michael Ströder wrote:
 
> For avoiding problems with errors like
> 
>   socket.error: (98, 'Address already in use.')
> 
> during immediate restart of my web server I'm following the hint to
> set the socket option SO_REUSEADDR. But I did not succeed. The
> server starts and works. When I stop it and try to restart
> immediately the above message appears again. I had a short look at
> man 7 socket and man setsockopt but this was a little bit too much
> for me...

> My code looks like this:
> 
> ------------------------ bite here -------------------------
> class MyHTTPServer(SocketServer.TCPServer):
> 
>   def server_bind(self):
>     """Override server_bind to set socket options."""
>     self.socket.setsockopt(
>       socket.getprotobyname('tcp'),
>       socket.SO_REUSEADDR,1
>     )
>     SocketServer.TCPServer.server_bind(self)
> ------------------------------------------------------------

You need socket.SOL_SOCKET, not 
socket.getprotobyname(). But there's still no substitute for a 
try / finally that closes the socket explicitly.




- Gordon




More information about the Python-list mailing list