A lot of people have written .NET equivalents of netstat code. Basically there are two starting points:
- Use the built-in System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties method, for instance by
– Build your own netstat.exe with c# | Tim Van Wassenhove.
– Netstat in C# « Towards Next. - A P/Invoke wrapper around the Windows IP Helper function GetExtendedTcpTable, which adds process information, for instance by
– windows – Which PID listens on a given port in c# – Stack Overflow.
– Netstat Example – CodeProject.
I adapted the first, made the output very much like the built-in Windows netstat, and added some LINQ code to demonstrate grouping and ordering.
Now you get grouped output like this:
Distinct Remote Address:Port pairs by Remote Address: 107.20.249.140 443 107.20.249.78 443 127.0.0.1 6421, 19872 192.168.1.81 17500, 61678 199.47.218.159 443 199.47.219.148 80 199.47.219.160 443 23.21.220.140 443 23.23.127.94 443
The code below is part of the DotNetStat example.
It demonstrates a few important LINQ aspects beyond the LINQ Query Expressions (C# Programming Guide) intro and 101 LINQ Samples in C#.:
- LINQ translates C# query keywords into framework members, for instance into extension methods in Enumerable Methods (System.Linq).
- LINQ uses delayed execution, so a lot of errors will not only absent during compile time, nor at LINQ query setup, but delayed until the portions of the query are being executed.
- In this case, it means that if you get the orderby wrong, you will get the an error like At least one object must implement IComparable inside the foreach loop.
- There is no distinct keyword, so you have to use one of the overloads of the Enumerable.Distinct Method (System.Linq).
- The group member by sub-member does not require an IComparable






