c#如何在列表中合计计数器ip
本文关键字:计数器 ip 列表 | 更新日期: 2023-09-27 17:51:05
我想统计系统中唯一IP地址的数量。
的例子:
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.1:xxx
- 127.0.0.1:80> 1.1.1.2:xxx
- 127.0.0.1:80> 1.1.1.3:xxx
- 127.0.0.1:80> 1.1.1.4:xxx
可以counter show 1.1.1.1(6), 1.1.1.2(1), 1.1.1.3(1), 1.1.1.4(1)
我的代码:
谢谢
static void Main(string[] args)
{
do
{
monitor();
System.Threading.Thread.Sleep(5000);
} while (true);
Console.ReadLine();
}
static void monitor()
{
string serverMonitor = "127.0.0.1:80";
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in tcpConnections)
{
string list = info.LocalEndPoint.Address.ToString() + ":" + info.LocalEndPoint.Port.ToString();
string remote = info.RemoteEndPoint.Address.ToString() + ":" + info.RemoteEndPoint.Port.ToString();
if (list == serverMonitor)
{
Console.WriteLine(list + " > " + remote + " [" + info.State.ToString() + "]");
}
}
Console.WriteLine("--------------------------------------------------");
}
清点一下,存到字典里。
Dictionary<string, int> ips = new Dictionary<string, int>();
// ...
foreach (var info in tcpConnections)
{
string list = info.LocalEndPoint.Address.ToString() + ":" + info.LocalEndPoint.Port.ToString();
string remote = info.RemoteEndPoint.Address.ToString() + ":" + info.RemoteEndPoint.Port.ToString();
if (list == serverMonitor)
{
if (ips.ContainsKey(remote))
ips[remote]++;
else
ips.Add(remote, 1);
}
}
foreach (var entry in ips)
{
Console.WriteLine("{0} ({1})", entry.Key, entry.Value);
}