I was surprised to discover that two servers I'm maintaining are both able to listen on port 3000 in development at the same time.
With the first server running, netstat shows
▶ sudo netstat -nap tcp | grep 3000
tcp6 0 0 ::1.3000 *.* LISTEN
tcp4 0 0 127.0.0.1.3000 *.* LISTEN
And with both running:
▶ sudo netstat -nap tcp | grep 3000
tcp4 0 0 *.3000 *.* LISTEN
tcp6 0 0 ::1.3000 *.* LISTEN
tcp4 0 0 127.0.0.1.3000 *.* LISTEN
My interpretation of this is that the first server has bound port 3000 only for localhost (127.0.0.1), and the second server has bound port 3000 for 'any' (0.0.0.0) address. Is that right?
The behaviour seems to be that the first server supersedes the other for traffic specifically to http://localhost:3000
, which makes sense I suppose. I just wanted to confirm my understanding for this slightly surprising scenario, I would have thought that trying to listen to 'any' address would fail if any address with that port was already bound.
bind
will fail for a conflict like this, but not if the program sets an option, originallySO_REUSEADDR
but may depend on OS; see stackoverflow.com/questions/14388706/… . Some programs do this automatically to allow restarting after a crash while 'orphaned' connections are still in TIME_WAIT.