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

MarianD
  • 2,726

1 Answers1

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 ... )
harrymc
  • 498,455