socket.unbind or socket.unlisten? - socket.error: (48, 'Address already in use')

Jean-Paul Calderone exarkun at divmod.com
Tue Jan 27 08:41:45 EST 2009


On Tue, 27 Jan 2009 10:49:03 +0100, Laszlo Nagy <gandalf at shopzeus.com> wrote:
>I have a program that uses socket.bind() and socket.listen() frequently. 
>After that program stops, it is not able to bind() again for a while:
>
>File "/home/gandalf/Python/Lib/orb/accesspoints/srvtcp.py", line 27, in 
>__init__
>    self.serversocket.bind((self.listen_address,self.port))
>  File "<string>", line 1, in bind
>socket.error: (48, 'Address already in use')
>
>
>The problem with this, is that this server program SOMETIMES need to be 
>restarted very quickly. I tried to find the solution in the socket module. 
>But there is no "socket.unbind" or "socket.unlisten". How can I tell the OS 
>that I do not want to listen on that address anymore, so other programs can 
>bind on it immediatelly?
>
>(Yes I know that I can use setsockopt to allow listening multiple sockets on 
>the same address, but this is NOT what I need...)

Actually, SO_REUSEADDR is probably just what you want.  Since I can't see
your code and I don't know under what situations it fails, I can only guess
at the problem, but my guess is that you have connections from the first run
of your app left in the TIME_WAIT state and they are preventing you from
binding to the address again in the second run of your app.  Setting the
SO_REUSEADDR flag on POSIX fixes this problem (don't set it on Windows,
though).

Jean-Paul



More information about the Python-list mailing list