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 { internal class Program { private static void Main(string[] args) { var all = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); if (all.Length == 0) { Console.WriteLine("Unexpected: GetActiveTcpConnections return 0 items."); return; } var allDic = all.GroupBy(p => p.State) .Select(p => new { State = p.Key, Count = p.Count() }) .ToDictionary(p => p.State, p => p.Count); PrintConnectionStat(allDic, ""); var topRemote = all.GroupBy(p => p.RemoteEndPoint.Address) .Select(p => new { Address = p.Key, Count = p.Count() }) .OrderByDescending(p => p.Count) .FirstOrDefault(); if(topRemote!=null) Console.WriteLine($" Top Remote Address: {topRemote.Address}, Connections: {topRemote.Count}"); if (args.Length != 0) { var dicTotal = new Dictionary(); 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); foreach (var kvp in portDic) { if (dicTotal.ContainsKey(kvp.Key)) dicTotal[kvp.Key] += kvp.Value; else dicTotal[kvp.Key] = kvp.Value; } } if (dicTotal.Count > 1) PrintConnectionStat(dicTotal, ""); } } private static void PrintConnectionStat(Dictionary allDic, string label) { Console.Write($" * Connections of {label}"); Console.Write($" TOTAL={allDic.Sum(p => p.Value)}"); foreach (var kvp in allDic) { Console.Write($" {kvp.Key}={kvp.Value}"); } Console.WriteLine(); } } }