Search code examples
windowslinuxtcpberkeley-sockets

difference between "address in use" with bind() in Windows and on Linux - errno=98


I have a small TCP server that listens on a port. While debugging it's common for me to CTRL-C the server in order to kill the process.

On Windows I'm able to restart the service quickly and the socket can be rebound. On Linux I have to wait a few minutes before bind() returns with success

When bind() is failing it returns errno=98, address in use.

I'd like to better understand the differences in implementations. Windows sure is more friendly to the developer, but I kind of doubt Linux is doing the 'wrong thing'.

My best guess is Linux is waiting until all possible clients have detected the old socket is broken before allowing new sockets to be created. The only way it could do this is to wait for them to timeout

is there a way to change this behavior during development in Linux? I'm hoping to duplicate the way Windows does this


Solution

  • You want to use the SO_REUSEADDR option on the socket on Linux. The relevant manpage is socket(7). Here's an example of its usage. This question explains what happens.

    Here's a duplicate of this answer.

    On Linux, SO_REUSEADDR allows you to bind to an address unless an active connection is present. On Windows this is the default behaviour. On Windows, SO_REUSEADDR allows you to additionally bind multiple sockets to the same addresses. See here and here for more.