Ejemplo n.º 1
0
        internal static List <ITcpConnectionInfo> GetTcp4Table()
        {
            int tableSize = 0;

            var result = GetTcpTable2(IntPtr.Zero, ref tableSize, false);

            IntPtr tcpTableRecordsPtr = IntPtr.Zero;

            List <ITcpConnectionInfo> fTable = new List <ITcpConnectionInfo>();

            try
            {
                tcpTableRecordsPtr = Marshal.AllocHGlobal(tableSize);

                result = GetTcpTable2(tcpTableRecordsPtr, ref tableSize, false);

                if (result != 0)
                {
                    return(fTable);
                }

                var table = Marshal.PtrToStructure <MIB_TCPTABLE2>(tcpTableRecordsPtr);

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

                for (int i = 0; i < table.dwNumEntries; ++i)
                {
                    MIB_TCPROW2 tcpRow = (MIB_TCPROW2)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_TCPROW2));

                    fTable.Add(new Tcp4ConnectionInfo(tcpRow));

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

                return(fTable);
            }
            catch (OutOfMemoryException me)
            {
                LoggerProxy.Default.Error(me);
            }
            catch (Exception e)
            {
                LoggerProxy.Default.Error(e);
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }

            return(fTable);
        }
Ejemplo n.º 2
0
        public Tcp4ConnectionInfo(MIB_TCPROW2 tcpRow)
        {
            // We mask the ports in this struct because according to the documentation, the upper
            // bits can be populated arbitrarily, aka undefined state.
            LocalPort = (ushort)(tcpRow.dwLocalPort & 0xFFFF);

            RemotePort = (ushort)(tcpRow.dwRemotePort & 0xFFFF);

            LocalAddress = new IPAddress(tcpRow.dwLocalAddr);

            RemoteAddress = new IPAddress(tcpRow.dwRemoteAddr);

            State = tcpRow.dwState;

            OffloadState = tcpRow.dwOffloadState;

            OwnerPid = tcpRow.dwOwningPid;
        }