3

我使用此代码获取 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 端口。

4

1 回答 1

3

使用TCP_TABLE_OWNER_PID_ALL代替,TCP_TABLE_OWNER_PID_LISTENER您将获得所有 TCP 端口。

于 2013-04-01T13:08:56.813 回答