unixsocketsbindport

Unix sockets programming: port is not getting unbound after server shutdown


I'm studying Unix sockets programming. I made a time server that sends raw time data and a client for it that receives that data and converts it to local time.

When I run the server, connect a client to it (which causes both of them to do their job and shutdown) and then rerun the server, I get errno = 98 on bind() call. I have to change the port in the server's source code and recompile it to get rid of that error. When I run the server and connect to it again it's ok, after another rerun the situation repeats. But I can change back to previous port then. So I'm jumping from port 1025 to 1026 and vice-versa each debug run (which are very frequent, so this annoys a little).

It works like this: The server opens the listener socket, binds to it, listens to it, accepts a connection into a data socket, writes a time_t to it, closes the data socket and then closes the listener socket. The client opens a socket, connects to a server, reads data and closes the socket.

What's the problem?

Thanks in advance.


Solution

  • The sockets have a lingering time after they close. They may keep the port taken for a litte while after the execution of your application, so they may send any unsent data. If you wait long enough the port will be released and can be taken again for another socket.

    For more info on Socket Lingering check out:

    https://web.archive.org/web/20100315050245/http://www.developerweb.net/forum/archive/index.php/t-2982.html