Search code examples
c#windows.net-coretcpclient

TCP Connection Creation and Closing Event Hooking


What helper classes C# provides to monitor all TCP connection on an OS. A piece of Sample code would also be appreciated.

Note: Original intent was to monitor this on Windows but would be nice to do the same on other os using .Net Core.


Solution

  • Assuming you want to monitor TCP Sockets on the machine, you can use System.Net.NetworkInformation.GetActiveTcpConnections which should give you a list of TCP connections and the current state of each. Which you can call on a regular timer to get updated states of the sockets.

    I am more familiar with the Win32 APIs for this, such as GetTcpTable and the less documented GetTcpTableEx, the later also provides the process ID of the process that ownes the local end point. So the above might not give exactly what I believe it does :)

    Of course if you need to be notified the very instant before or after a tcp socket is created or it's state changes, that unfortunately would require a kernel mode driver which cannot be written in .NET.