How do I make sure that a socket bound to a port is properly released on process exit such that the port can be reused without bind() failing with EADDRINUSE? I’ve written a tiny program which just creates a socket, binds it to a fixed port, waits for a connection and then immediately terminates. When I rerun the program, the bind() call fails with EADDRINUSE, but if I wait a few minutes, it succeeds.
Is there a way I can explicitly ‘unbind’ the socket, thereby freeing the port number?
Using SO_REUSEADDR socket option will allow you to re-start the program without delay.