Get all TCP-connections opened by application using C#
Asked Answered
B

2

6

How to find all tcp connections opened by specific application, maybe by process id or smth. like this? I use C#

Bagwig answered 22/8, 2011 at 9:21 Comment(1)
Check out if this helps: #5401110Tahiti
I
8

This project can help you :Getting active TCP/UDP connections

Inoculation answered 22/8, 2011 at 9:37 Comment(1)
[DllImport("Iphlpapi.dll", CharSet = CharSet.Ansi)] public static extern int AllocateAndGetTcpExTableFromStack(); is 'no longer available' as #71307488Intuitionism
S
1

Here is an easy code-snippet to get all connections with their PIDs:

using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.InteropServices;

public static class TcpHelper {

    [DllImport("iphlpapi.dll", SetLastError = true)]
    private static extern uint GetExtendedTcpTable(IntPtr tcpTable, ref int tcpTableLength, bool sort, int ipVersion, int tcpTableType, int reserved);

    [StructLayout(LayoutKind.Sequential)]
    public struct TcpRow {
        public uint state;
        private uint localAddr;
        private byte localPort1, localPort2, localPort3, localPort4;
        private uint remoteAddr;
        private byte remotePort1, remotePort2, remotePort3, remotePort4;
        public int owningPid;
        public string LocalAddress {get {return new IPAddress(localAddr).ToString();}}
        public string RemoteAddress {get {return new IPAddress(remoteAddr).ToString();}}
        public int LocalPort  {get {return (localPort1 << 8) + localPort2;}}
        public int RemotePort {get {return (remotePort1 << 8) + remotePort2;}}
    }

    public static List<TcpRow> GetExtendedTcpTable() {
        List<TcpRow> tcpRows = new List<TcpRow>();

        IntPtr tcpTablePtr = IntPtr.Zero;
        try {
            int tcpTableLength = 0;
            if (GetExtendedTcpTable(tcpTablePtr, ref tcpTableLength, false, 2, 5, 0) != 0) {
                tcpTablePtr = Marshal.AllocHGlobal(tcpTableLength);
                if (GetExtendedTcpTable(tcpTablePtr, ref tcpTableLength, false, 2, 5, 0) == 0) {
                    TcpRow tcpRow = new TcpRow();
                    IntPtr currentPtr = tcpTablePtr + Marshal.SizeOf(typeof(uint));

                    for (int i = 0; i < tcpTableLength / Marshal.SizeOf(typeof(TcpRow)); i++) {
                        tcpRow = (TcpRow)Marshal.PtrToStructure(currentPtr, typeof(TcpRow));
                        if (tcpRow.RemoteAddress != "0.0.0.0") {tcpRows.Add(tcpRow);}
                        currentPtr += Marshal.SizeOf(typeof(TcpRow));
                    }
                }
            }
        }
        finally {
            if (tcpTablePtr != IntPtr.Zero) {
                Marshal.FreeHGlobal(tcpTablePtr);
            }
        }
        return tcpRows;
    }
}
Sand answered 6/7, 2024 at 19:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.