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,uint reserved = 0);

VB Signature:

<DllImport("iphlpapi.dll", SetLastError:=True)> _
Public Shared Function GetExtendedTcpTable(ByVal pTcpTable As IntPtr, ByRef dwOutBufLen As Integer, ByVal sort As Boolean, ByVal ipVersion As  Integer, ByVal tblClass As TCP_TABLE_CLASS, ByVal reserved As Integer) As UInteger
End Function

User-Defined Types:

TCP_TABLE_CLASS

Notes:

When you do not need the PID information look at: IPGlobalProperties.GetActiveTcpListeners Method from the System.Net.NetworkInformation namespace

(Msdn: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalproperties.getactivetcplisteners.aspx)

Sample Code:

Generic methods for IPv4 and IPv6. Using MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID, MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID and TCP_TABLE_CLASS

public const int AF_INET = 2;    // IP_v4 = System.Net.Sockets.AddressFamily.InterNetwork
public const int AF_INET6 = 23;  // IP_v6 = System.Net.Sockets.AddressFamily.InterNetworkV6

public static List<MIB_TCPROW_OWNER_PID> GetAllTCPConnections()
{
    return GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET);
}

public static List<MIB_TCP6ROW_OWNER_PID> GetAllTCPv6Connections()
{
    return GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6);
}

private static List<IPR> GetTCPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
{
    IPR[] tableRows;
    int buffSize = 0;

    var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");

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

    try
    {
        ret = GetExtendedTcpTable(tcpTablePtr, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
        if (ret != 0)
            return new List<IPR>();

        // get the number of entries in the table
        IPT table = (IPT)Marshal.PtrToStructure(tcpTablePtr, typeof(IPT));
        int rowStructSize = Marshal.SizeOf(typeof(IPR));
        uint numEntries = (uint)dwNumEntriesField.GetValue(table);

        // buffer we will be returning
        tableRows = new IPR[numEntries];

        IntPtr rowPtr = (IntPtr)((long)tcpTablePtr + 4);
        for (int i = 0; i < numEntries; i++)
        {
            IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
            tableRows[i] = tcpRow;
            rowPtr = (IntPtr)((long)rowPtr + rowStructSize);   // next entry
        }
    }
    finally
    {
        // Free the Memory
        Marshal.FreeHGlobal(tcpTablePtr);
    }
    return tableRows != null ? tableRows.ToList() : new List<IPR>();
}

Sample Code:

Previous sample

public MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
{
    MIB_TCPROW_OWNER_PID[] 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);        
    IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

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

        // get the number of entries in the table
        MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
        IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
        tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

        for (int i = 0; i < tab.dwNumEntries; i++)
        {
            MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
            tTable[i] = tcpRow;
            rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));   // next entry
        }
    }
    finally
    {
        // Free the Memory
        Marshal.FreeHGlobal(buffTable);
    }
    return tTable;
}

Documentation