using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Reflection; [assembly: AssemblyTitle("ConnectionStat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConnectionStat")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] namespace ConnectionStat { class Program { static void Main(string[] args) { var all = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); if (all.Length == 0) { Console.WriteLine("GetActiveTcpConnections return 0 items."); return; } var allDic = all.GroupBy(p => p.State).Select(p => new { State = p.Key, Count = p.Count() }).Where(p => p.Count != 0).ToDictionary(p => p.State, p => p.Count); if (args.Length == 0) { PrintConnectionStat(allDic, "All"); } else { foreach (var argString in args) { if (!int.TryParse(argString, out var port)) continue; var filterByPort = all.Where(p => p.LocalEndPoint.Port == port); var portDic = filterByPort.GroupBy(p => p.State).Select(p => new { State = p.Key, Count = p.Count() }).Where(p => p.Count != 0).ToDictionary(p => p.State, p => p.Count); PrintConnectionStat(portDic, "Port " + port); } } } private static void PrintConnectionStat(Dictionary allDic, string label) { Console.WriteLine($" * Connections of {label}"); foreach (var kvp in allDic) { Console.Write($" {kvp.Key}={kvp.Value}"); } Console.WriteLine($" TOTAL={allDic.Sum(p => p.Value)}"); Console.WriteLine(); } } }