Program.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.NetworkInformation;
  5. using System.Reflection;
  6. [assembly: AssemblyTitle("ConnectionStat")]
  7. [assembly: AssemblyDescription("")]
  8. [assembly: AssemblyConfiguration("")]
  9. [assembly: AssemblyCompany("")]
  10. [assembly: AssemblyProduct("ConnectionStat")]
  11. [assembly: AssemblyCopyright("Copyright © 2022")]
  12. [assembly: AssemblyTrademark("")]
  13. [assembly: AssemblyCulture("")]
  14. [assembly: AssemblyVersion("1.0.0.0")]
  15. [assembly: AssemblyFileVersion("1.0.0.0")]
  16. namespace ConnectionStat
  17. {
  18. class Program
  19. {
  20. static void Main(string[] args)
  21. {
  22. var all = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
  23. if (all.Length == 0)
  24. {
  25. Console.WriteLine("GetActiveTcpConnections return 0 items.");
  26. return;
  27. }
  28. 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);
  29. if (args.Length == 0)
  30. {
  31. PrintConnectionStat(allDic, "All");
  32. }
  33. else
  34. {
  35. foreach (var argString in args)
  36. {
  37. if (!int.TryParse(argString, out var port)) continue;
  38. var filterByPort = all.Where(p => p.LocalEndPoint.Port == port);
  39. 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);
  40. PrintConnectionStat(portDic, "Port " + port);
  41. }
  42. }
  43. }
  44. private static void PrintConnectionStat(Dictionary<TcpState, int> allDic, string label)
  45. {
  46. Console.WriteLine($" * Connections of {label}");
  47. foreach (var kvp in allDic)
  48. {
  49. Console.Write($" {kvp.Key}={kvp.Value}");
  50. }
  51. Console.WriteLine($" TOTAL={allDic.Sum(p => p.Value)}");
  52. Console.WriteLine();
  53. }
  54. }
  55. }