[Tutor] seeking help to a problem w/ sockets

Martin Walsh mwalsh at groktech.org
Sun Apr 27 15:36:54 CEST 2008

James Duffy wrote:
> I have a problem w/ a file transfer receiver. They way it works is it
> binds a port for incoming transfer , when the file transfer is complete.
> It closes the connection and the socket, then loops back and restarts
> the bind and listen. I have it set so that the socket is reuseable,
> which is why this works. However, if the program that is using this
> function is closed while listening, it appears that it does not
> ”un-bind” because when the program is reopened and a listen attepted to
> start I get a “port already in use” error. Only a reboot fixes this
> issue. This code is imported into a main GUI script. We have it set to
> execute some cleanup functions on exit, I need a function that can dig

It should be noted that my socket, threading, and related gui skillz are
lacking, so beware.

IIUC, the usual cause for an 'address already in use' error is when the
server closes it's end of the socket first, leaving it in a TIME_WAIT
state. Presumably, this would be a feature of tcp, and the socket is
released after some timeout period to be sure the client is no longer
communicating. However setting the socket options as you have, with
setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), is the typically
suggested workaround in this situation.

Also, given that you need to reboot to clear the error, I suspect that
your gui program isn't actually terminating -- but instead hanging on
the Receiver thread, and thus holding on to the socket. You can, of
course, confirm with netstat and/or by checking the process list. If you
just want the thread to die when you close the gui app, then you could
also try to setDaemon(True) on your Receiver class -- which should allow
the program to exit, that is -- if there are no non-daemon threads


More information about the Tutor mailing list