How can I force close TcpListener

I have a service that communicates via tcpListener. The problem is when the user restarts the service - the exception "Address is already in use" is thrown, and the service cannot be started for a couple of minutes or so.

Is there a way to tell the system to stop the old connection so that I can open a new one? (I canโ€™t just use random ports because there is no way for the service to notify clients what the port is, so we must depend on the predefined port)

+4
source share
2 answers

Set the SO_REUSEADDR socket SO_REUSEADDR before binding to the listening port. It seems that the corresponding .NET code looks something like this:

 SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); 
+3
source

There is a reason that sockets are not used for some time after they are closed. The socket consists of 4 tuples: Source and Dest Port, Source and Dest IP.

Let's say you close the socket a lot and the client was busy sending data to the server. You wait 5 seconds and reopen the server with the same port, and the same client sends data to the same 4 tuples, the server will receive packets with incorrect tcp sequence numbers, and the connections will be reset.

You shoot yourself in the foot :)

This is why the connections have the time_wait status for 2-4 minutes (depending on the distribution) until they are reused. To be clear, I'm talking about SOCKET, not just the tcp listening port.

+1
source

Source: https://habr.com/ru/post/1312133/


All Articles