Пример #1
0
 private ConnectionInfo ConnectionInformation(MIB_TCPROW_OWNER_PID rawConection)
 {
     return(new ConnectionInfo()
     {
         LocalPort = rawConection.LocalPort,
         LocalIP = rawConection.LocalIP,
         RemotePort = rawConection.RemotePort,
         RemoteIP = rawConection.RemoteIP,
         Pid = rawConection.Pid,
         Status = (ConnectionStatus)rawConection.state,
     });
 }
Пример #2
0
        private MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            //Based on http://stackoverflow.com/questions/577433/which-pid-listens-on-a-given-port-in-c-sharp
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET    = 2; // IP_v4
            int bufferSize = 0;

            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            if (ret != 0 && ret != 122)
            {
                throw new Exception("bad ret on check " + ret);
            }
            IntPtr buffTable = Marshal.AllocHGlobal(bufferSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref bufferSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    throw new Exception("bad ret " + ret);
                }

                // 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   += Marshal.SizeOf(tcpRow);
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }