All discussion I've seen on SO_REUSEADDR
assumes that it's the same program creating and binding to a TCP socket on a known port.
I have two different programs using the same port, and I'm curious about how the mechanism works -- in order for program 2 to allocate a port program 1 has just closed, do they both have to specify SO_REUSEADDR
after they create the socket?
Or is it enough for one of them? If so, the one taking the socket first or the one trying to open it afterwards, when it's lingering in TIME_WAIT state?
Here's a small example in Python to hopefully make the case clearer;
# one.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", 5050)) # Assuming 5050 is available
sys.exit(1) # Assuming s enters TIME_WAIT
# two.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", 5050))
s.listen()
Think of one.py and two.py as two separate codebases.
Does both one.py and two.py need to set the SO_REUSEADDR
socket option in order for two.py to tolerate a lingering TIME_WAIT socket from one.py?
Thank you.
To answer your question. I believe that on Linux you have to specify SO_REUSEADDR
ONLY in the program that wants to reuse the port. Very simple. On Microsoft Windows however, this is a different story. Microsoft has a page on MSDN that covers SO_REUSEADDR and related features.