Search code examples
linuxsocketsnetwork-programmingbindlisten

why would I get EADDRINUSE not from bind() but from listen()?


In a C++ Linux application I'm calling socket(), bind() and listen(), to create a server socket. Usually if the application is started twice (with same server port), in the second process bind() will fail with EADDRINUSE error. However, now I have a case where bind() has apparently succeeded but the subsequent listen() call has thrown the EADDRINUSE error...

This is probably a rare race condition, but I'd be still interested in what cases it could happen that the second bind() succeeds but the second listen() does not. Does anyone know more about such a case?

This is on 32-bit RHEL 5.3.


Solution

  • Not sure about Linux, but on Windows, if a wildcard IP (INADDR_ANY, etc) is specified when calling bind(), the underlying binding may be delayed until listen() or connect() is called, as the OS has a better chance of deciding at that time which network interface is best to use. bind() will not report an error in that situation.