GetExtendedTcpTable (iphlpapi)
Last changed: -165.214.11.85

.
Summary
The GetExtendedTcpTable function retrieves a table that contains a list of TCP endpoints available to the application.

C# Signature:

[DllImport("iphlpapi.dll", SetLastError=true)]
static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass,int reserved);

VB Signature:

Declare Function GetExtendedTcpTable Lib "iphlpapi.dll" (TODO) As TODO

User-Defined Types:

None.

Alternative Managed API:

Do you know one? Please contribute it!

Notes:

Tips & Tricks:

Please add some!

Sample Code:

    public TcpRow[] GetAllTcpConnections()
    {
    //  TcpRow is my own class to display returned rows in a nice manner.
        TcpRow[] tTable;
        int AF_INET = 2;    // IP_v4
        int buffSize = 0;

        // how much memory do we need?
        uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL,0);        
        IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

        try
        {
        ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
        if (ret != 0)
        {
            return null;
        }

        // get the number of entries in the table
        MibTcpTable tab = (MibTcpTable)Marshal.PtrToStructure(buffTable, typeof(MibTcpTable));
        IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.numberOfEntries) );

        // buffer we will be returning
        tTable = new TcpRow[tab.numberOfEntries];

        for (int i = 0; i < tab.numberOfEntries; i++)        
        {
            MibTcpRow_Owner_Pid tcpRow = (MibTcpRow_Owner_Pid)Marshal.PtrToStructure(rowPtr, typeof(MibTcpRow_Owner_Pid));
            tTable[i] = new TcpRow(tcpRow);
            rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));   // next entry
        }

        }
        finally
        {
        // Free the Memory
        Marshal.FreeHGlobal(buffTable);
        }

        return tTable;
    }

Documentation