概述:通过 PID 获取进程的端口。
思路说明
主要是通过 GetExtendedTcpTable
获取系统当前所有的 TCP 连接。通过获取到的数据结构体 PMIB_TCPTABLE_OWNER_PID
中的参数 dwOwningPid 来判断当前端口所属进程,从而达到获取当前进程端口的目的。
相关接口
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| UINT16 GetProcessPort(DWORD dwProcesId) { PMIB_TCPTABLE_OWNER_PID pTcpTable = NULL; DWORD dwSize = 0; DWORD dwNum = 0; UINT16 uLocalPort = 0; if (dwProcesId == 0) { return uLocalPort; }
do { if (GetExtendedTcpTable(pTcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER) { break; } pTcpTable = (MIB_TCPTABLE_OWNER_PID*)new(std::nothrow) char[dwSize]; if (!pTcpTable) { break; } if (GetExtendedTcpTable(pTcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != NO_ERROR) { MYTRACE(L"[GetProcessPort] GetExtendedTcpTable failed (%d)\n", GetLastError()); break; } dwNum = pTcpTable->dwNumEntries; for (DWORD i = 0; i < dwNum; i++) { if (pTcpTable->table[i].dwOwningPid == dwProcesId) { uLocalPort = htons((u_short)pTcpTable->table[i].dwLocalPort); break; } }
} while (0);
if (pTcpTable != NULL) { char * pT = (char *)pTcpTable; delete[] pT; }
return uLocalPort; }
|