Originally published on the old depletionmode / 2of1 blog (archived copy).
The linux kernel will automatically lock up a port on bind() – even if the process is killed.
Well actually the kernel will close the socket when the process ends, however it stays in the 2MSL (2 x Max. Segment Lifetime) state for a few (2) minutes.
That means that the next time you try to bind() the port, you could get a message saying that it is already in use.
This is VERY annoying – especially if you’re trying to debug a TCP server for example.
The solution for this is to have your program instruct the kernel to allow a new socket to be bound to the same port. You can do this by setting the SO_REUSEADDR sockopt as follows:
int opt = 1;
setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));