我使用此代码获取PC中已打开端口的列表以及使用每个端口的应用程序。
string Port::GetListOfTcpPorts()
{
string ApplicationName = "";
string result = "";
string aux = "";
string RemotePort = "";
DWORD (WINAPI *pGetExtendedTcpTable)(
PVOID pTcpTable,
PDWORD pdwSize,
BOOL bOrder,
ULONG ulAf,
TCP_TABLE_CLASS TableClass,
ULONG Reserved
);
MIB_TCPTABLE_OWNER_PID *pTCPInfo;
MIB_TCPROW_OWNER_PID *owner;
DWORD size;
DWORD dwResult;
HMODULE hLib = LoadLibrary("iphlpapi.dll");
pGetExtendedTcpTable = (DWORD (WINAPI *)(PVOID,PDWORD,BOOL,ULONG,TCP_TABLE_CLASS,ULONG))
GetProcAddress(hLib, "GetExtendedTcpTable");
dwResult = pGetExtendedTcpTable(NULL, &size, false, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0);
pTCPInfo = (MIB_TCPTABLE_OWNER_PID*)malloc(size);
dwResult = pGetExtendedTcpTable(pTCPInfo, &size, false, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0);
for (DWORD dwLoop = 0; dwLoop < pTCPInfo->dwNumEntries; dwLoop++)
{
owner = &pTCPInfo->table[dwLoop];
ApplicationName = GetNameByPID(owner->dwOwningPid);
OpenedPort = convertInt(ntohs(owner->dwLocalPort));
RemotePort = convertInt(ntohs(owner->dwRemotePort));
aux = "TCP ; " + OpenedPort + ";"+ RemotePort+";"+ ApplicationName + "\n";
result = result + aux;
}
return result;
}
但是,如果我将结果与netstat -ano
的结果进行比较,则此函数不会返回所有TCP端口。
答案 0 :(得分:3)
使用TCP_TABLE_OWNER_PID_ALL
代替TCP_TABLE_OWNER_PID_LISTENER
,您将获得所有TCP端口。