13

If my C program uses sockets, binds to localhost:9025, exchanges some data, gets manually killed and restarted, it sometimes crashes with the error being:

Address already in use.

All SE-recommended software that I've tried to look for “pid that uses port” with have failed to return any process id, so I assume there is no process at that time that uses port 9025, which should be the case.

Nonetheless, from what I've gathered from comments on topically similar questions, it seemed to me that "Address" is "already in use" if and only if a process uses that particular address. Why is this false then?

Now I assume the OS keeps track of what addresses are in use and what are not, but is that the case? If it is though, I would love if you could tell me how do I correct it, because my best solution to this problem is “wait for an undetermined amount of time”.

EDIT: I use Linux 5.2.2-arch1-1-ARCH x86_64

3

1 Answer 1

32

You are probably re-starting your program too fast, or the program is not closing the socket.

Even after the socket is closed, Linux keeps the connection in limbo for some time, but will prevent any other connection from being accepted for the same quadruplet of "source address, source port, destination address, destination port".

The solution is to set the socket option in the program with setsockopt like this:

setsockopt(socket,SOL_SOCKET,SO_REUSEADDR ... )
12
  • 1
    SO_REUSEADDR promises that your program will not get confused by data arriving for a previous instance of the program. For TCP, that is pretty much given. Aug 26, 2019 at 6:38
  • 1
    While SO_REUSEADDR is the commonly used approach (and indeed what I'd recommend, too), be aware that it is not 100% safe. There exists a small chance that delayed packets are wrongfully delivered to the new socket (if there happen to be any at all, and if they happen to have the right remote port, etc.). Alas, most people deem this an acceptable risk, seeing how it's rather unlikely to be encountered and the benefits (server up again instantly rather than after 2 minutes) usually outweight the risk.
    – Damon
    Aug 26, 2019 at 8:18
  • @Damon note that randomized TCP sequence numbers mean the chance of wrongful delivery of a packet to the new process is less than 1 in 2^32. Aug 26, 2019 at 14:17
  • @Damon Isn't the delay even 256 seconds instead of 2 minutes (because of TTL magic), or am I mixing tat up with something? Aug 26, 2019 at 14:35
  • See unix.stackexchange.com/questions/17218/… for a short program to measure this delay. Note that SO_REUSEADDR makes it impossible to distinguish new connections from different clients behind the same NAT. Aug 26, 2019 at 15:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .