在C#中获取电脑上所有打开端口的详细连接信息通常涉及到网络编程和系统级别的操作。这可以通过多种方式实现,但最常见的方法之一是使用System.Net命名空间中的类,并结合系统级别的API调用。下面是一些步骤和示例代码,帮助你获取电脑上所有打开端口的详细连接信息。
方法1:使用System.Net.NetworkInformation
System.Net.NetworkInformation命名空间提供了访问网络接口信息和网络统计信息的功能。你可以使用IPGlobalProperties.GetIPGlobalProperties()来获取当前计算机的IP全局属性,然后使用GetActiveTcpListeners()和GetActiveTcpConnections()方法来查看TCP连接。
示例代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
class Program
{
static void Main()
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();
Console.WriteLine("Active TCP Listeners:");
foreach (var listener in tcpListeners)
{
Console.WriteLine($"Port: {listener.Port}");
}
var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
Console.WriteLine("\nActive TCP Connections:");
foreach (var connection in tcpConnections)
{
Console.WriteLine($"LocalEndPoint: {connection.LocalEndPoint}, RemoteEndPoint: {connection.RemoteEndPoint}, State: {connection.State}");
}
}
}
方法2:使用P/Invoke调用Windows API
如果你需要更详细的控制或者需要访问更多底层信息,你可以使用P/Invoke调用Windows API,如netstat命令的底层API。例如,使用netstat -ano的底层API可以让你获取到每个连接的PID等信息。
示例代码(使用P/Invoke调用netstat):
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
[DllImport("iphlpapi.dll", ExactSpelling = true)]
private static extern int SendARP(uint ip, uint mac, byte[] pa, ref uint size);
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern uint GetIpAddrTable(IntPtr pIPAddrTable, ref uint pSize, bool bOrder);
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern int GetExtendedTcpTable(IntPtr pTcpTable, ref uint dwOutBufLen, bool sort, int ipVersion, TcpTableType tableClass, uint reserved);
private enum TcpTableType : uint { OwnerPidOnly = 5 };
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private const int IP_ADAPTER_INFO_SIZE = 8 * 1024;
private const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
private const int MAX_ADAPTER_NAME_LENGTH = 256;
private const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
private const int GAA_FLAG_INCLUDE_PREFIX = 16;
private const int MIB_TCP_STATE_LISTENING = 2;
private const int MIB_TCP_STATE_ESTABLISHED = 4;
private const int MIB_TCP_STATE_CLOSE_WAIT = 8;
}
注意:直接使用P/Invoke调用底层API相对复杂且容易出错,特别是涉及到权限和网络编程的细节问题。通常建议先尝试使用System.Net.NetworkInformation类,如果需要更详细的信息再考虑使用P/Invoke。此外,获取某些信息可能需要管理员权限。对于大多数应用场景,直接使用System.Net.NetworkInformation应该已经足够。
相关文档:
C#获取电脑上所有打开端口的详细连接信息[
1]
http://29190.oa22.cn
【C#】如何判断当前是否开启了远程桌面连接[
4927]
http://16624.oa22.cn
C#如何判断Windows Server远程桌面有异常登录,并获知当前登录用户名?[
3550]
http://16722.oa22.cn
该文章在 2025/2/12 10:11:15 编辑过