setsockopt, SO_REUSEADDR question
Stephen J. Turner
sjturner at ix.netcom.com
Thu May 27 10:21:59 EDT 1999
Constantinos A. Kotsokalis wrote:
>
> Hello people,
> pardon me if this has been answered before, couldn't find any trails.
> I have the following code:
>
> addr = '127.0.0.1', 5050
> srv = SocketServer.ThreadingTCPServer(addr, handle_con)
> srv.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
> srv.serve_forever()
>
> Everything is working as expected, except for the fact that the
> setsockopt does not do what i'd like it to. I understand it's
> highly possible I've passed wrong arguments but could not find
> any help on the right ones. What I want it to do is to be able to
> start a server on port 5050, even if another server was just shut
> down and there's still a closing listen socket there. Since it does
> not work, I have to wait about 30 sec between each run of my
> program.
> Any advice, please?
>
> Thank you,
> Costas
The problem is that the SO_REUSEADDR socket option must be set before
the address is bound to the socket. This can be done by subclassing
ThreadingTCPServer and overriding the server_bind method as follows:
import SocketServer, socket
class MyThreadingTCPServer(SocketServer.ThreadingTCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
Regards,
Stephen
--
Stephen J. Turner <sjturner at ix.netcom.com>
More information about the Python-list
mailing list