如何查找特定应用程序打开的所有 tcp 连接,可能是通过进程 ID 或其他方式。像这样?我用C#
这个项目可以帮助您:获取活动的 TCP/UDP 连接
这里有一个简单的代码片段,用于获取所有连接及其 PID:
public static class TcpHelper {
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern uint GetExtendedTcpTable(IntPtr tcpTable, ref int tcpTableLength, bool sort, int ipVersion, int tcpTableType, int reserved);
[StructLayout(LayoutKind.Sequential)]
public struct TcpRow {
public uint state;
public uint localAddr;
public byte localPort1, localPort2, localPort3, localPort4;
public uint remoteAddr;
public byte remotePort1, remotePort2, remotePort3, remotePort4;
public int owningPid;
}
public static List<TcpRow> GetExtendedTcpTable() {
List<TcpRow> tcpRows = new List<TcpRow>();
IntPtr tcpTablePtr = IntPtr.Zero;
try {
int tcpTableLength = 0;
if (GetExtendedTcpTable(tcpTablePtr, ref tcpTableLength, false, 2, 5, 0) != 0) {
tcpTablePtr = Marshal.AllocHGlobal(tcpTableLength);
if (GetExtendedTcpTable(tcpTablePtr, ref tcpTableLength, false, 2, 5, 0) == 0) {
TcpRow tcpRow = new TcpRow();
IntPtr currentPtr = tcpTablePtr + Marshal.SizeOf(typeof(uint));
for (int i = 0; i < tcpTableLength / Marshal.SizeOf(typeof(TcpRow)); i++) {
tcpRow = (TcpRow)Marshal.PtrToStructure(currentPtr, typeof(TcpRow));
tcpRows.Add(tcpRow);
currentPtr += Marshal.SizeOf(typeof(TcpRow));
}
}
}
}
finally {
if (tcpTablePtr != IntPtr.Zero) {
Marshal.FreeHGlobal(tcpTablePtr);
}
}
return tcpRows;
}
}