如何使用.NET Framework获取所有活动的TCP连接(没有非托管PE导入!)?

Rol*_*oll 13 .net c# sockets

如何使用.NET Framework获取所有活动的TCP连接(没有非托管PE导入!)?

我正在进入socket编程,想要检查一下.在我的研究中,我通过导入一个我不感兴趣的非托管DLL文件找到了解决方案.

Rol*_*oll 26

我很惊讶用户的数量告诉我无法使用纯托管代码...对于想知道这一点的未来用户,请从答案中找到对我有用的详细信息:

//Don't forget this:
using System.Net.NetworkInformation;

public static void ShowActiveTcpConnections()
{
    Console.WriteLine("Active TCP Connections");
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
    foreach (TcpConnectionInformation c in connections)
    {
        Console.WriteLine("{0} <==> {1}",
                          c.LocalEndPoint.ToString(),
                          c.RemoteEndPoint.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

并呼吁ShowActiveTcpConnections()列出它,真棒和美丽.

来源:IPGlobalProperties.GetActiveTcpConnections方法(MSDN)

  • 我知道我迟到了,但如果这就是你正在做的事情,你可以让它变得更简单,`foreach(var c in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections())` (2认同)