We know that TCPview, for example, can close the TCP connection for the other process without closing the process. So how to implement it? Suppose there is a process connecting to the a remote ip and port, how to terminate that connection?

The following image shows the TCP/IP connection state. Using in .NET the class Socket, when we call the method Socket.Close, we can see with TCPView the used port remain for a while in the state TIME_WAIT, before to free that port. This is quite normal, but how can we avoid this? The TIME_WAIT has its utility, but sometimes we just don’t need it.

TCP-CLOSE_WAIT.png

TCPView can close every connection just clicking on “Close Connection”? How can it do this? A way to reach this is goal is calling the Windows API.

Cattura.PNG

To call the Windows API you need, first of all, to write the signature of the called method. To help you with this activity, there pinvoke.net, a Visual Studio Extension created to help developers to search for the right signature.

In this case, we need to call the closesocket method, so the signature is:

[DllImport("ws2_32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int closesocket(IntPtr s);

Simply, to use it, call it in this way:

closesocket(socket.Handle);

Calling this will close immediatly the connection. Call it only once from the client (I mean the side waiting for the last answer). When you do this, the connection will close also from server side. (check it with TCPView, just to be sure)

As you can see from the pinvoke site (or also from the Visual Studio Extension, if you installed it), there are a lot of Windows API you can call, depending on your needs.

 

Advertisements