Nissim
Nissim

Reputation: 6563

How can I forcibly close a TcpListener

I have a service which communicates through tcpListener. Problem is when the user restarts the service - an "Address already in use" exception is thrown, and the service cannot be started for a couple of minutes or so.

Is there's any way of telling the system to terminate the old connection so I can open a new one? (I can't just use random ports because there is no way for the service to notify the clients what is the port, so we must depend on a predefined port)

Upvotes: 4

Views: 2824

Answers (2)

eitama
eitama

Reputation: 1507

There is a reason sockets are not used for some time after they are closed. A Socket is comprised of a 4 tuple, Source and Dest Port, Source and Dest IP.

Let's say you close a socket forcefully, while the client was busy sending data to the server. You wait 5 seconds and re-open the server with the same Port, and the same client sends data to the same 4 tuple, the server will get packets with wrong tcp sequence numbers, and the connections will get reset.

You are shooting yourself in the foot :)

This is why connections have a time_wait status for 2-4 minutes (depending on distro) until they can be used again. Just to be clear, i'm talking about SOCKETs and not just the listening tcp port.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994531

Set the SO_REUSEADDR socket option before binding to the listening port. It looks like the corresponding .NET code is something like:

SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

Upvotes: 4

Related Questions