Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot bind to address after socket program crashes

Tags:

python

sockets

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)?

like image 499
Jeffrey Aylesworth Avatar asked Feb 16 '10 02:02

Jeffrey Aylesworth


People also ask

Why would a socket bind fail?

If you're seeing a "TCP/UDP: Socket bind failed on local address" error message in the OpenVPN log, it means your VPN connection is configured to bind to a fixed local address and/or port number, and that this address/port number is unavailable.

What does bind function do in socket programming?

The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called.


1 Answers

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.

like image 164
ephemient Avatar answered Sep 23 '22 06:09

ephemient