Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are two processes listening to the same port in Windows 7?

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....

  1. Why/How does this work? Is this behavior useful in some context?
  2. I don't want an instance to successful run if another application is going to catch the incoming requests... How do I make the port exclusive?
like image 520
Olson Avatar asked Sep 10 '12 13:09

Olson


1 Answers

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:

  1. 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.

  2. 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.)

like image 158
selbie Avatar answered Oct 11 '22 02:10

selbie