123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 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, "<ALL IN THIS HOST>");
- 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<TcpState, int>();
- 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, "<SUM OF LISTED PORTS>");
- }
- }
- private static void PrintConnectionStat(Dictionary<TcpState, int> 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();
- }
- }
- }
|