Microsoft Docs – Windows API Reference

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

NameDescription
pTcpTablePointer to a buffer that receives the TCP table data. The caller must allocate enough memory. Set to NULL to retrieve the required size.
pdwSizeOn input, specifies the size of the buffer pointed to by pTcpTable. On output, receives the required size if the buffer is too small.
bOrderIf TRUE, the entries are sorted in ascending order by local address.
ulAfAddress family: AF_INET for IPv4 or AF_INET6 for IPv6.
TableClassOne of the TCP_TABLE_CLASS enumeration values that determines the type of information returned.
ReservedMust 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

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;
}

See also