tags:

views:

289

answers:

2

If my program crashes before a socket is closed, the next time I run in, I get an error that looks like this;

socket.error: [Errno 48] Address already in use

Changing the port fixes the problem.

Is there any way to avoid this, and why does this happen (when the program exits, shouldn't the socket be garbage collected, and closed)?

+10  A: 

Use .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) on your listening socket.

A search for those terms will net you many explanations for why this is necessary. Basically, after your first program closes down, the OS keeps the previous listening socket around in a shutdown state for TIME_WAIT time. SO_REUSEADDR says that you want to use the same listening port regardless.

ephemient
+1  A: 

Most OSes take up to 2 minutes to close the socket when the program doesn't properly close it first. I've hit this many times with C programs that SEGFAULT (and I don't have it handled) or similar.

Edit:
Thanks to ephemient for pointing out RFC 793 (TCP) which defines this timeout.

Chris S
RFC 793 (TCP) says that `TIME_WAIT` should be 2MSL, which defaults to 2 minutes, unless further FIN packets are received. 5 minutes would be unusually long.
ephemient