How does the OS tell whether an "Address is already in use"?

Solution 1:

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