GetExtendedTcpTable
Header: iphlpapi.h
Library: Iphlpapi.lib
DLL: Iphlpapi.dll
Syntax
DWORD GetExtendedTcpTable(
PVOID pTcpTable,
PDWORD pdwSize,
BOOL bOrder,
ULONG ulAf,
TCP_TABLE_CLASS TableClass,
ULONG Reserved
);
Parameters
| Name | Description |
|---|---|
pTcpTable | Pointer to a buffer that receives the TCP table data. The caller must allocate enough memory. Set to NULL to retrieve the required size. |
pdwSize | On input, specifies the size of the buffer pointed to by pTcpTable. On output, receives the required size if the buffer is too small. |
bOrder | If TRUE, the entries are sorted in ascending order by local address. |
ulAf | Address family: AF_INET for IPv4 or AF_INET6 for IPv6. |
TableClass | One of the TCP_TABLE_CLASS enumeration values that determines the type of information returned. |
Reserved | Must be zero. |
Return value
If the function succeeds, the return value is NO_ERROR (0). Otherwise, it returns a Win32 error code such as ERROR_INSUFFICIENT_BUFFER (122).
Remarks
- The buffer returned by
pTcpTablecontains a structure whose layout depends on theTableClassvalue. For example,TCP_TABLE_OWNER_PID_ALLreturns aMIB_TCPTABLE_OWNER_PIDstructure. - When querying IPv6 data, set
ulAftoAF_INET6and use the corresponding IPv6 structures such asMIB_TCP6TABLE_OWNER_PID. - The function requires the calling process to have appropriate privileges to view connections owned by other processes.
Examples
#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>
#pragma comment(lib, "Iphlpapi.lib")
int main()
{
DWORD dwSize = 0;
GetExtendedTcpTable(NULL, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
BYTE* buffer = (BYTE*)malloc(dwSize);
if (buffer == NULL) { printf("Memory allocation failed\n"); return 1; }
DWORD dwResult = GetExtendedTcpTable(buffer, &dwSize, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0);
if (dwResult == NO_ERROR) {
PMIB_TCPTABLE_OWNER_PID pTcpTable = (PMIB_TCPTABLE_OWNER_PID)buffer;
printf("Number of entries: %lu\n", pTcpTable->dwNumEntries);
for (DWORD i = 0; i < pTcpTable->dwNumEntries; ++i) {
MIB_TCPROW_OWNER_PID row = pTcpTable->table[i];
printf("%d.%d.%d.%d:%d -> %d.%d.%d.%d:%d PID:%lu State:%d\n",
(row.dwLocalAddr & 0xFF), (row.dwLocalAddr >> 8) & 0xFF,
(row.dwLocalAddr >> 16) & 0xFF, (row.dwLocalAddr >> 24) & 0xFF,
ntohs((u_short)row.dwLocalPort),
(row.dwRemoteAddr & 0xFF), (row.dwRemoteAddr >> 8) & 0xFF,
(row.dwRemoteAddr >> 16) & 0xFF, (row.dwRemoteAddr >> 24) & 0xFF,
ntohs((u_short)row.dwRemotePort),
row.dwOwningPid,
row.dwState);
}
} else {
printf("GetExtendedTcpTable failed with error %lu\n", dwResult);
}
free(buffer);
return 0;
}