Exemple #1
0
        public static MIB_TCPROW_OWNER_PID[] GetTable()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int    AF_INET   = 2;
            int    buffSize  = 0;
            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);
                }
                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));
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
Exemple #2
0
            public static 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,
                                               0);

                if (ret != 0 && ret != 122) // 122 insufficient buffer size
                {
                    throw new Exception("bad ret on check " + ret);
                }
                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)
                    {
                        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;
                        // next entry
                        rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
                finally
                {
                    // Free the Memory
                    Marshal.FreeHGlobal(buffTable);
                }
                return(tTable);
            }
        public static List <TcpRecordPid> GetAllTcpConnections()
        {
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // getting the memory size needed
            uint val = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            if (val != 0 && val != 122)
            {
                throw new Exception("invalid size " + val);
            }

            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
            List <TcpRecordPid> lstRecords = new List <TcpRecordPid>();

            try
            {
                val = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

                if (val != 0)
                {
                    throw new Exception("ivalid data " + val);
                }

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

                for (int i = 0; i < tcpTable.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    //tTable[i] = tcpRow;
                    lstRecords.Add(new TcpRecordPid(
                                       new IPAddress(tcpRow.localAddr),
                                       new IPAddress(tcpRow.remoteAddr),
                                       BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort2, tcpRow.localPort1
                    }, 0),                                                                                // reverse order
                                       BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort2, tcpRow.remotePort1
                    }, 0),                                                                                // reverse order
                                       tcpRow.owningPid,
                                       tcpRow.state));
                    // next entry
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(lstRecords);
        }
        //public TcpRow[] GetAllTcpConnections()
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            if (getAllTcpConnections_cached == null || getAllTcpConnections_cached_lastTime + new TimeSpan(0, 0, 1) < DateTime.Now)
            {
                //  TcpRow is my own class to display returned rows in a nice manner.
                //    TcpRow[] tTable;
                MIB_TCPROW_OWNER_PID[] tTable;
                int AF_INET  = 2;   // IP_v4
                int buffSize = 0;

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

                try
                {
                    ret = NativeMethods.GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                    if (ret != 0)
                    {
                        return(new MIB_TCPROW_OWNER_PID[0]);
                    }

                    // get the number of entries in the table
                    //MibTcpTable tab = (MibTcpTable)Marshal.PtrToStructure(buffTable, typeof(MibTcpTable));
                    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.numberOfEntries) );
                    IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                    // buffer we will be returning
                    //tTable = new TcpRow[tab.numberOfEntries];
                    tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];

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


                getAllTcpConnections_cached          = tTable;
                getAllTcpConnections_cached_lastTime = DateTime.Now;
            }

            return(getAllTcpConnections_cached);
        }
        //return the MIB_TCPROW_OWNER_PID array as connection
        public MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;


            // what the size of the memory we need to allocate for the table?
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            //set pointer to buffer
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);


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


                //convert pointer to MIB_TCPTABLE_OWNER_PID pointer
                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];


                //reading the row from buffer using next position pointer
                //size of MIB_TCPROW_OWNER_PID
                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    //convert pointer to MIB_TCPROW_OWNER_PID pointer
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    //save row in table
                    tTable[i] = tcpRow;
                    //go to the next entry.
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // clear buffer
                Marshal.FreeHGlobal(buffTable);
            }


            return(tTable);
        }
Exemple #6
0
        internal List <Tcp> GetExtendedTcpTable()
        {
            int AF_INET  = 2;
            int buffSize = 20000;

            byte[] buffer = new byte[buffSize];

            int res = GetExtendedTcpTable(buffer, out buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);

            if (res != NO_ERROR)
            {
                throw new InvalidOperationException("Error get extended tcp table");
            }

            MIB_TCPTABLE_OWNER_PID tcpExtendedTable = new MIB_TCPTABLE_OWNER_PID();
            int nOffset = 0;

            tcpExtendedTable.dwNumEntries = Convert.ToInt32(buffer[nOffset]);
            nOffset += 4;
            tcpExtendedTable.table = new MIB_TCPROW_OWNER_PID[tcpExtendedTable.dwNumEntries];
            for (int i = 0; i < tcpExtendedTable.dwNumEntries; i++)
            {
                int st = Convert.ToInt32(buffer[nOffset]);
                tcpExtendedTable.table[i].State   = ConvertState(st);
                tcpExtendedTable.table[i].dwState = st;
                nOffset += 4;
                tcpExtendedTable.table[i].Local       = BufferToIPEndPoint(buffer, ref nOffset, false);
                tcpExtendedTable.table[i].Remote      = BufferToIPEndPoint(buffer, ref nOffset, true);
                tcpExtendedTable.table[i].dwOwningPid = BufferToInt(buffer, ref nOffset);
                tcpExtendedTable.table[i].ProcessName = GetProcessName(tcpExtendedTable.table[i].dwOwningPid);
            }
            List <Tcp> tcps = new List <Tcp>();

            for (int i = 0; i < tcpExtendedTable.table.Length; i++)
            {
                Tcp tcp = new Tcp {
                    ProcessId = tcpExtendedTable.table[i].dwOwningPid, LocalIp = tcpExtendedTable.table[i].Local.Address.ToString(), LocalPort = tcpExtendedTable.table[i].Local.Port, RemoteIp = tcpExtendedTable.table[i].Remote.Address.ToString(), RemotePort = tcpExtendedTable.table[i].Remote.Port, ProcessName = tcpExtendedTable.table[i].ProcessName, State = tcpExtendedTable.table[i].State
                };
                if (HideLocal && (tcp.LocalIp == "0.0.0.0" || tcp.LocalIp == "127.0.0.1"))
                {
                    continue;
                }
                tcps.Add(tcp);
            }
            return(tcps);
        }
Exemple #7
0
        public MIB_TCPROW_OWNER_PID[] SelectAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // calculate memory usage
            uint   res       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                res = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
                if (res != 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));

                // buffer we will be returning
                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;

                    //getting the next entry
                    //  C/C++  baseAddress+= sizeof( MIB_TCPROW_OWNER_PID);
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }



            return(tTable);
        }
Exemple #8
0
        public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            MIB_TCPROW_OWNER_PID[] tcpConnectionRows;
            int AF_INET  = 2;   // IPv4
            int buffSize = 0;

            // use WinAPI GetExtendedTcpTable to query all active tcp connection information
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);

            if (ret != 0 && ret != 122) // 122 means insufficient buffer size
            {
                throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
            }
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_TYPE.TCP_TABLE_OWNER_PID_ALL, 0);
                if (ret != 0)
                {
                    throw new Exception("Error occurred when trying to query tcp table, return code: " + ret);
                }

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

                for (int i = 0; i < table.dwNumEntries; i++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tcpConnectionRows[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            finally
            {
                // free memory
                Marshal.FreeHGlobal(buffTable);
            }
            return(tcpConnectionRows);
        }
        public MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            // TcpRow is my own class to display returned rows in a nice manner.
            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));
                // buffer we will be returning;
                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);
        }
Exemple #10
0
        public static MIB_TCPROW_OWNER_PID[] GetTcpTableEx()
        {
            MIB_TCPROW_OWNER_PID[] tTable;

            int buffSize = 0;

            // Determine much memory is needed
            uint   ret       = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, (int)AddressFamily.InterNetwork, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(buffTable, ref buffSize, true, (int)(int)AddressFamily.InterNetwork, 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));

                // buffer we will be returning
                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);
        }
Exemple #11
0
        private static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
        {
            const int NO_ERROR = 0;
            const int IP_v4    = 2;

            MIB_TCPROW_OWNER_PID[] tTable = null;
            int buffSize = 0;

            GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, IP_v4, TCP_TABLE_OWNER_PID_ALL, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                if (NO_ERROR != GetExtendedTcpTable(buffTable, ref buffSize, true, IP_v4, TCP_TABLE_OWNER_PID_ALL, 0))
                {
                    return(null);
                }
                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];

                int rowSize = Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID));
                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 + rowSize);
                }
            }
            catch { }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
Exemple #12
0
        public static List <TcpProcessRecord> GetAllTcpConnections()
        {
            int bufferSize = 0;
            List <TcpProcessRecord> tcpTableRecords = new List <TcpProcessRecord>();

            // Getting the size of TCP table, that is returned in 'bufferSize' variable.
            uint result = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, AF_INET,
                                              TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

            // Allocating memory from the unmanaged memory of the process by using the
            // specified number of bytes in 'bufferSize' variable.
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The size of the table returned in 'bufferSize' variable in previous
                // call must be used in this subsequent call to 'GetExtendedTcpTable'
                // function in order to successfully retrieve the table.
                result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true,
                                             AF_INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                // Non-zero value represent the function 'GetExtendedTcpTable' failed,
                // hence empty list is returned to the caller function.
                if (result != 0)
                {
                    return(new List <TcpProcessRecord>());
                }

                // Marshals data from an unmanaged block of memory to a newly allocated
                // managed object 'tcpRecordsTable' of type 'MIB_TCPTABLE_OWNER_PID'
                // to get number of entries of the specified TCP table structure.
                MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)
                                                         Marshal.PtrToStructure(tcpTableRecordsPtr,
                                                                                typeof(MIB_TCPTABLE_OWNER_PID));
                IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr +
                                              Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                // Reading and parsing the TCP records one by one from the table and
                // storing them in a list of 'TcpProcessRecord' structure type objects.
                for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.
                                                  PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    tcpTableRecords.Add(new TcpProcessRecord(
                                            new IPAddress(tcpRow.localAddr),
                                            new IPAddress(tcpRow.remoteAddr),
                                            BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort[1],
                        tcpRow.localPort[0]
                    }, 0),
                                            BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort[1],
                        tcpRow.remotePort[0]
                    }, 0),
                                            tcpRow.owningPid, tcpRow.state));
                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            catch (OutOfMemoryException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }
            return(tcpTableRecords != null?tcpTableRecords.Distinct()
                   .ToList <TcpProcessRecord>() : new List <TcpProcessRecord>());
        }
Exemple #13
0
        /// <summary>
        /// Add to list TCP connections using IPv4.
        /// </summary>
        /// <param name="table"></param>
        static void GetIPv4Info(MIB_TCPTABLE_OWNER_PID* table)
        {
            uint tblSize = table->dwNumEntries; // Number of elements in table.
            var firstRow = &table->table;       // The first element in table.

            for (uint i = 0; i < tblSize; ++i)
            {
                MIB_TCPROW_OWNER_PID row = firstRow[i];
                SocketList.Add(new CSocket("TCP", row.dwLocalAddr, row.dwLocalPort, row.dwRemoteAddr, row.dwRemotePort, row.dwOwningPid, row.dwState));
            }
        }
Exemple #14
0
        //根据端口找PID
        private void TrySetProcessId(int port)
        {
            int bufferSize = 0;

            uint   result             = GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                result = GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, INET, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));

                IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                {
                    MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));
                    int localPort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort[1], tcpRow.localPort[0]
                    }, 0);
                    int remotePort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort[1], tcpRow.remotePort[0]
                    }, 0);
                    int pid = tcpRow.owningPid;

                    if (localPort == port)
                    {
                        Process p = Process.GetProcessById(pid);
                        //IE比较烦,要获取最先启动的那个主进程 这里不知道怎么找,暂时通过启动时间找,是否靠谱待验证
                        if (p.ProcessName == "iexplore")
                        {
                            DateTime  time  = DateTime.MaxValue;
                            Process[] procs = Process.GetProcessesByName("iexplore");
                            for (int ii = 0; ii < procs.Length; ii++)
                            {
                                if (time == DateTime.MaxValue)
                                {
                                    pid  = procs[ii].Id;
                                    time = procs[ii].StartTime;
                                    continue;
                                }
                                else if (procs[ii].StartTime < time)
                                {
                                    pid  = procs[ii].Id;
                                    time = procs[ii].StartTime;
                                    continue;
                                }
                            }
                        }
                        this.ProcessId = pid;
                        break;
                    }

                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));

                    //IPAddress localIp, IPAddress remoteIp, ushort localPort,ushort remotePort, int pId, MibTcpState state
                    //tcpTableRecords.Add(new TcpProcessRecord(
                    //                      new IPAddress(tcpRow.localAddr),
                    //                      new IPAddress(tcpRow.remoteAddr),
                    //                      BitConverter.ToUInt16(new byte[2] {
                    //                          tcpRow.localPort[1],
                    //                          tcpRow.localPort[0] }, 0),
                    //                      BitConverter.ToUInt16(new byte[2] {
                    //                          tcpRow.remotePort[1],
                    //                          tcpRow.remotePort[0] }, 0),
                    //                      tcpRow.owningPid, tcpRow.state));
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }
        }
Exemple #15
0
        public static List <TcpConnectionInfo> GetTcpConnections(IPVersion ipVersion, Dictionary <int, Process> processesByPid = null)
        {
            int bufferSize = 0;
            List <TcpConnectionInfo> tcpTableRecords = new List <TcpConnectionInfo>();

            int ulAf = AF_INET;

            if (ipVersion == IPVersion.IPv6)
            {
                ulAf = AF_INET6;
            }

            // Getting the initial size of TCP table.
            uint result = Iphlpapi.GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, ulAf, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

            // Allocating memory as an IntPtr with the bufferSize.
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The IntPtr from last call, tcpTableRecoresPtr must be used in the subsequent
                // call and passed as the first parameter.
                result = Iphlpapi.GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, ulAf, TcpTableClass.TCP_TABLE_OWNER_PID_ALL);

                // If not zero, the call failed.
                if (result != 0)
                {
                    return(new List <TcpConnectionInfo>());
                }

                // Marshals data fron an unmanaged block of memory to the
                // newly allocated managed object 'tcpRecordsTable' of type
                // 'MIB_TCPTABLE_OWNER_PID' to get number of entries of TCP
                // table structure.

                // Determine if IPv4 or IPv6.
                if (ipVersion == IPVersion.IPv4)
                {
                    MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCPTABLE_OWNER_PID));

                    IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                    // Read and parse the TCP records from the table and store them in list
                    // 'TcpConnection' structure type objects.
                    for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                    {
                        MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW_OWNER_PID));

                        // Add row to list of TcpConnetions.
                        tcpTableRecords.Add(new TcpConnectionInfo(
                                                Protocol.TCP,
                                                new IPAddress(tcpRow.localAddr),
                                                new IPAddress(tcpRow.remoteAddr),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.localPort[1],
                            tcpRow.localPort[0]
                        }, 0),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.remotePort[1],
                            tcpRow.remotePort[0]
                        }, 0),
                                                tcpRow.owningPid,
                                                tcpRow.state,
                                                GetProcessNameByPid(tcpRow.owningPid, processesByPid)));

                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
                else if (ipVersion == IPVersion.IPv6)
                {
                    MIB_TCP6TABLE_OWNER_PID tcpRecordsTable = (MIB_TCP6TABLE_OWNER_PID)Marshal.PtrToStructure(tcpTableRecordsPtr, typeof(MIB_TCP6TABLE_OWNER_PID));

                    IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr + Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                    // Read and parse the TCP records from the table and store them in list
                    // 'TcpConnection' structure type objects.
                    for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                    {
                        MIB_TCP6ROW_OWNER_PID tcpRow = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCP6ROW_OWNER_PID));

                        tcpTableRecords.Add(new TcpConnectionInfo(
                                                Protocol.TCP,
                                                new IPAddress(tcpRow.localAddr, tcpRow.localScopeId),
                                                new IPAddress(tcpRow.remoteAddr, tcpRow.remoteScopeId),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.localPort[1],
                            tcpRow.localPort[0]
                        }, 0),
                                                BitConverter.ToUInt16(new byte[2] {
                            tcpRow.remotePort[1],
                            tcpRow.remotePort[0]
                        }, 0),
                                                tcpRow.owningPid,
                                                tcpRow.state,
                                                GetProcessNameByPid(tcpRow.owningPid, processesByPid)));

                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                    }
                }
            }
            catch (OutOfMemoryException outOfMemoryException)
            {
                throw outOfMemoryException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }

            return(tcpTableRecords != null?tcpTableRecords.Distinct().ToList() : new List <TcpConnectionInfo>());
        }
Exemple #16
0
        private static Connection[] GetTCP()
        {
            MIB_TCPROW_OWNER_PID[] tTable;
            int AF_INET  = 2;
            int buffSize = 0;

            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)
                {
                    Connection[] con = new Connection[0];
                    return(con);
                }

                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
            {
                Marshal.FreeHGlobal(buffTable);
            }

            Connection[] cons = new Connection[tTable.Length];

            for (int i = 0; i < tTable.Length; i++)
            {
                IPAddress localip   = new IPAddress(BitConverter.GetBytes(tTable[i].dwLocalAddr));
                IPAddress remoteip  = new IPAddress(BitConverter.GetBytes(tTable[i].dwRemoteAddr));
                byte[]    barray    = BitConverter.GetBytes(tTable[i].dwLocalPort);
                int       localport = (barray[0] * 256) + barray[1];
                barray = BitConverter.GetBytes(tTable[i].dwRemotePort);
                int    remoteport = (barray[0] * 256) + barray[1];
                string state;
                switch (tTable[i].dwState)
                {
                case 1:
                    state = "Closed";
                    break;

                case 2:
                    state = "LISTENING";
                    break;

                case 3:
                    state = "SYN SENT";
                    break;

                case 4:
                    state = "SYN RECEIVED";
                    break;

                case 5:
                    state = "ESTABLISHED";
                    break;

                case 6:
                    state = "FINSIHED 1";
                    break;

                case 7:
                    state = "FINISHED 2";
                    break;

                case 8:
                    state = "CLOSE WAIT";
                    break;

                case 9:
                    state = "CLOSING";
                    break;

                case 10:
                    state = "LAST ACKNOWLEDGE";
                    break;

                case 11:
                    state = "TIME WAIT";
                    break;

                case 12:
                    state = "DELETE TCB";
                    break;

                default:
                    state = "UNKNOWN";
                    break;
                }
                Connection tmp = new Connection(localip, localport, remoteip, remoteport, (int)tTable[i].dwOwningPid, state);
                cons[i] = (tmp);
            }
            return(cons);
        }