I am running two instances of stunnel in Windows 7, configured to listen to the same port, and it appears that they are both successfully listening on the same port (just using socket()/bind()/listen()). Both instances appear to succeed with all calls and they show up in a netstat:
C:\>netstat -ano | grep 8000
TCP 0.0.0.0:8000 0.0.0.0:0 LISTENING 5828
TCP 0.0.0.0:8000 0.0.0.0:0 LISTENING 5852
The first one to listen gets all incoming requests.
This is pretty much opposite to all my expectations. (I was expecting to get EADDRINUSE telling me the port was busy.) So....
This can be accomplished if the socket was opened with the flag SO_REUSEADDR, which is not uncommon for TCP socket applications.
Typically, SO_REUSEADDR is used for one of two things:
When a process has crashed, been killed, or forcibly restarted without getting a chance to close its sockets. Or the process exited but the socket (or child connection socket) is still in a FIN_WAIT or FIN_WAIT2 state. The second process can open the socket without getting an "already in use" error code. I've read a couple of posts on S.O. suggesting that this is a best practice for TCP sockets.
The same server program either forked or run multiple times concurrently. This allows for load balancing without the server program written to make use of threads. Typically, the "other instance" of the program listening on the socket will accept incoming connections while the first is busy with another connection.
In regards to your second question, the easiest thing to do is not use SO_REUSEADDR. If you are concerned that there might be a rogue app that does try to use SO_REUSADDR, then your app can use SO_EXCLUSIVEADDRUSE. (A flag, which basically says, "don't allow other apps to open this same port with SO_REUSEADDR.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With