Program.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. internal class Program
  19. {
  20. private static void Main(string[] args)
  21. {
  22. var all = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
  23. if (all.Length == 0)
  24. {
  25. Console.WriteLine("Unexpected: GetActiveTcpConnections return 0 items.");
  26. return;
  27. }
  28. var allDic = all.GroupBy(p => p.State)
  29. .Select(p => new { State = p.Key, Count = p.Count() })
  30. .ToDictionary(p => p.State, p => p.Count);
  31. PrintConnectionStat(allDic, "<ALL IN THIS HOST>");
  32. var topRemote = all.GroupBy(p => p.RemoteEndPoint.Address)
  33. .Select(p => new { Address = p.Key, Count = p.Count() })
  34. .OrderByDescending(p => p.Count)
  35. .FirstOrDefault();
  36. if(topRemote!=null) Console.WriteLine($" Top Remote Address: {topRemote.Address}, Connections: {topRemote.Count}");
  37. if (args.Length != 0)
  38. {
  39. var dicTotal = new Dictionary<TcpState, int>();
  40. foreach (var argString in args)
  41. {
  42. if (!int.TryParse(argString, out var port)) continue;
  43. var filterByPort = all.Where(p => p.LocalEndPoint.Port == port);
  44. 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);
  45. PrintConnectionStat(portDic, "Port " + port);
  46. foreach (var kvp in portDic)
  47. {
  48. if (dicTotal.ContainsKey(kvp.Key)) dicTotal[kvp.Key] += kvp.Value;
  49. else dicTotal[kvp.Key] = kvp.Value;
  50. }
  51. }
  52. if (args.Length > 1) PrintConnectionStat(dicTotal, "<SUM OF LISTED PORTS>");
  53. }
  54. }
  55. private static void PrintConnectionStat(Dictionary<TcpState, int> allDic, string label)
  56. {
  57. Console.Write($" * Connections of {label}");
  58. Console.Write($" TOTAL={allDic.Sum(p => p.Value)}");
  59. foreach (var kvp in allDic)
  60. {
  61. Console.Write($" {kvp.Key}={kvp.Value}");
  62. }
  63. Console.WriteLine();
  64. }
  65. }
  66. }