在Windows的"netstat"实用程序的较新版本中,有一个命令行选项"-q"显示绑定但未连接的套接字。
关于此类套接字的输出如下所示
TCP 0.0.0.0:4294 0.0.0.0:0 BOUND
TCP 0.0.0.0:8054 0.0.0.0:0 BOUND
TCP 0.0.0.0:8840 0.0.0.0:0 BOUND
我在类似 netstat 的程序中使用 GetExtendedTcpTable 来监视某些应用程序(由 pid 或".exe"名称标识(消耗的资源(内存、句柄、线程、连接(,但我相信这个 API 只显示连接信息,而不是套接字信息,因此,它不提供绑定但未连接的套接字的信息。
那么,哪个Windows API可以用来在C++程序中捕获这些信息呢?
Windows 目前没有任何记录或受支持的 API 来查询绑定连接。唯一的替代方法是使用这两个未记录的函数:
ULONG WINAPI InternalGetBoundTcpEndpointTable(
_Out_ PMIB_TCPTABLE2* BoundTcpTable,
_In_ PVOID HeapHandle,
_In_opt_ ULONG HeapFlags
);
ULONG WINAPI InternalGetBoundTcp6EndpointTable(
_Out_ PMIB_TCP6TABLE2* BoundTcp6Table,
_In_ PVOID HeapHandle,
_In_opt_ ULONG HeapFlags
);
例:
#pragma comment(lib, "iphlpapi.lib")
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <windows.h>
#include <stdio.h>
ULONG WINAPI InternalGetBoundTcpEndpointTable(
_Out_ PMIB_TCPTABLE2* BoundTcpTable,
_In_ PVOID HeapHandle,
_In_opt_ ULONG HeapFlags
);
ULONG WINAPI InternalGetBoundTcp6EndpointTable(
_Out_ PMIB_TCP6TABLE2* BoundTcp6Table,
_In_ PVOID HeapHandle,
_In_opt_ ULONG HeapFlags
);
void main()
{
PMIB_TCPTABLE2 boundTcpTable;
PMIB_TCP6TABLE2 boundTcp6Table;
if (InternalGetBoundTcpEndpointTable(&boundTcpTable, GetProcessHeap(), 0) == ERROR_SUCCESS)
{
for (ULONG i = 0; i < boundTcpTable->dwNumEntries; i++)
{
printf("%lu: %lun",
boundTcpTable->table[i].dwOwningPid,
boundTcpTable->table[i].dwLocalPort);
}
HeapFree(GetProcessHeap(), 0, boundTcpTable);
}
if (InternalGetBoundTcp6EndpointTable(&boundTcp6Table, GetProcessHeap(), 0) == ERROR_SUCCESS)
{
for (ULONG i = 0; i < boundTcp6Table->dwNumEntries; i++)
{
printf("%lu: %lun",
boundTcp6Table->table[i].dwOwningPid,
boundTcp6Table->table[i].dwLocalPort);
}
HeapFree(GetProcessHeap(), 0, boundTcp6Table);
}
}