Exemple #1
0
        internal void GetExtendedUdpTable()
        {
            int AF_INET  = 2;
            int buffSize = 20000;

            byte[] buffer = new byte[buffSize];

            int res = GetExtendedUdpTable(buffer, out buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);

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

            MIB_UDPTABLE_OWNER_PID udpExtendedTable = new MIB_UDPTABLE_OWNER_PID();
            int nOffset = 0;

            udpExtendedTable.dwNumEntries = Convert.ToInt32(buffer[nOffset]);
            nOffset += 4;
            udpExtendedTable.table = new MIB_UDPROW_OWNER_PID[udpExtendedTable.dwNumEntries];
            for (int i = 0; i < udpExtendedTable.dwNumEntries; i++)
            {
                udpExtendedTable.table[i].Local       = BufferToIPEndPoint(buffer, ref nOffset, false);
                udpExtendedTable.table[i].dwOwningPid = BufferToInt(buffer, ref nOffset);
                udpExtendedTable.table[i].ProcessName = GetProcessName(udpExtendedTable.table[i].dwOwningPid);
            }
        }
        //return the MIB_UDPROW_OWNER_PID array


        public MIB_UDPROW_OWNER_PID[] GetAllUdpConnections()
        {
            MIB_UDPROW_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 = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
            //set pointer to buffer
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);


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


                //convert pointer to MIB_UDPTABLE_OWNER_PID pointer
                MIB_UDPTABLE_OWNER_PID tab = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_UDPTABLE_OWNER_PID));


                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));


                tTable = new MIB_UDPROW_OWNER_PID[tab.dwNumEntries];


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


            return(tTable);
        }
        //public TcpRow[] GetAllTcpConnections()
        public static MIB_UDPROW_OWNER_PID[] GetAllUdpConnections()
        {
            if (getAllUdpConnections_cached == null || getAllUdpConnections_cached_lastTime + new TimeSpan(0, 0, 1) < DateTime.Now)
            {
                MIB_UDPROW_OWNER_PID[] tTable;
                int AF_INET  = 2;   // IP_v4
                int buffSize = 0;

                // how much memory do we need?
                uint   ret       = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

                try
                {
                    ret = GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                    if (ret != 0)
                    {
                        return(new MIB_UDPROW_OWNER_PID[0]);
                    }

                    // get the number of entries in the table
                    //MibTcpTable tab = (MibTcpTable)Marshal.PtrToStructure(buffTable, typeof(MibTcpTable));
                    MIB_UDPTABLE_OWNER_PID tab = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_UDPTABLE_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_UDPROW_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_UDPROW_OWNER_PID tcpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_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);
                }


                getAllUdpConnections_cached          = tTable;
                getAllUdpConnections_cached_lastTime = DateTime.Now;
            }

            return(getAllUdpConnections_cached);
        }
Exemple #4
0
        public static List <UdpRecordPid> GetAllUdpConnections()
        {
            int AF_INET  = 2;   // IP_v4
            int buffSize = 0;

            // getting the memory size needed
            uint val = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);

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

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

            try
            {
                val = GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);

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

                // get the number of entries in the table
                MIB_UDPTABLE_OWNER_PID udpTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_UDPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(udpTable.dwNumEntries));

                for (int i = 0; i < udpTable.dwNumEntries; i++)
                {
                    MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    lstRecords.Add(new UdpRecordPid(
                                       new IPAddress(udpRow.localAddr),
                                       BitConverter.ToUInt16(new byte[2] {
                        udpRow.localPort2, udpRow.localPort1
                    }, 0),                                                                                // reverse order
                                       udpRow.owningPid));
                    // next record
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(udpRow));
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(lstRecords.Distinct().ToList <UdpRecordPid>());
        }
Exemple #5
0
        private static Connection[] GetUDP()
        {
            MIB_UDPROW_OWNER_PID[] tTable;
            int AF_INET  = 2; // IP_v4
            int buffSize = 0;

            uint   ret       = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
            IntPtr buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
                if (ret != 0)
                {//none found
                    Connection[] con = new Connection[0];
                    return(con);
                }
                MIB_UDPTABLE_OWNER_PID tab = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_UDPTABLE_OWNER_PID));
                IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));
                tTable = new MIB_UDPROW_OWNER_PID[tab.dwNumEntries];

                for (int i = 0; i < tab.dwNumEntries; i++)
                {
                    MIB_UDPROW_OWNER_PID udprow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    tTable[i] = udprow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(udprow));
                }
            }
            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));
                byte[]     barray    = BitConverter.GetBytes(tTable[i].dwLocalPort);
                int        localport = (barray[0] * 256) + barray[1];
                Connection tmp       = new Connection(localip, localport, (int)tTable[i].dwOwningPid);
                cons[i] = tmp;
            }
            return(cons);
        }
Exemple #6
0
        private static MIB_UDPTABLE_OWNER_PID[] getCurrentUDPListeners()
        {
            int buflen;

            MIB_UDPTABLE_OWNER_PID[] tableContents;
            int res = GetExtendedUdpTable(IntPtr.Zero, out buflen, false, 2, UDP_TABLE_OWNER_PID, 0);

            if (res != 122) // error_more_data
            {
                throw new Win32Exception(res, "GetExtendedUdpTable (first) failed");
            }
            IntPtr tableBuffer = Marshal.AllocHGlobal(buflen);

            try
            {
                res = GetExtendedUdpTable(tableBuffer, out buflen, false, 2, UDP_TABLE_OWNER_PID, 0);
                if (res != 0)
                {
                    throw new Win32Exception(res, "GetExtendedUdpTable (second) failed");
                }
                UDP_TABLE_CLASS table = (UDP_TABLE_CLASS)Marshal.PtrToStructure(tableBuffer, typeof(UDP_TABLE_CLASS));
                tableContents = new MIB_UDPTABLE_OWNER_PID[(buflen - Marshal.SizeOf(typeof(UDP_TABLE_CLASS))) / Marshal.SizeOf(typeof(MIB_UDPTABLE_OWNER_PID))];

                for (int rowIndex = 0; rowIndex < tableContents.Length; rowIndex++)
                {
                    IntPtr pos = tableBuffer +
                                 Marshal.SizeOf(typeof(UDP_TABLE_CLASS)) +
                                 ((Marshal.SizeOf(typeof(MIB_UDPTABLE_OWNER_PID))) * rowIndex);
                    MIB_UDPTABLE_OWNER_PID row = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(pos, typeof(MIB_UDPTABLE_OWNER_PID));

                    row.localPort = byteswap((UInt16)row.localPort);

                    tableContents[rowIndex] = row;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(tableBuffer);
            }

            return(tableContents);
        }
Exemple #7
0
        public static void ensurePortIsFree(UInt16 port)
        {
            MIB_UDPTABLE_OWNER_PID[] tableContents = getCurrentUDPListeners();
            MIB_UDPTABLE_OWNER_PID   portUse       = tableContents.SingleOrDefault(x => x.localPort == port);

            if (portUse == null)
            {
                return;
            }

            using (Process p = Process.GetProcessById((int)portUse.ownerPID))
            {
                p.Kill();
                p.WaitForExit((int)TimeSpan.FromSeconds(5).TotalMilliseconds);
                if (!p.HasExited)
                {
                    throw new Exception("Unable to kill PID " + portUse.ownerPID + " which is using needed port " + portUse.localPort);
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// This routine determines the UDP listener endpoint for the server.
        /// </summary>
        /// <param name="Script">Supplies the caller's script object.</param>
        /// <returns>The listener endpoint for the server.</returns>
        public static IPEndPoint GetServerUdpListener(CLRScriptBase Script)
        {
            int    CurrentProcessId = Process.GetCurrentProcess().Id;
            uint   TableSize        = 0;
            IntPtr Table            = IntPtr.Zero;
            uint   Status           = NO_ERROR;
            int    LocalPort;

            //
            // If we have cached the data, return it from the cache.
            //
            // It is important to check the cache if we spin up a secondary
            // UDP socket (and that the cache is first set before that is done)
            // or else we might return the wrong listener.
            //

            if ((LocalPort = Script.GetGlobalInt("ACR_SERVERLISTENER_PORT")) != 0)
            {
                return(new IPEndPoint((long)(UInt32)Script.GetGlobalInt("ACR_SERVERLISTENER_ADDRESS"), LocalPort));
            }

            //
            // Find the first UDP listener owned by this process and assume
            // that it's the right one.
            //

            try
            {
                do
                {
                    if (Table != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(Table);
                        Table = IntPtr.Zero;
                    }

                    if (TableSize != 0)
                    {
                        Table = Marshal.AllocHGlobal((int)TableSize);
                    }

                    Status = GetExtendedUdpTable(Table, ref TableSize, 1, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
                } while (Status == ERROR_INSUFFICIENT_BUFFER);

                if (Status != NO_ERROR)
                {
                    throw new ApplicationException(String.Format("ALFA.SystemInfo.GetServerUdpListener: GetExtendedUdpTable failed, status = {0}", Status));
                }

                MIB_UDPTABLE_OWNER_PID UdpTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(Table, typeof(MIB_UDPTABLE_OWNER_PID));

                for (uint Row = 0; Row < UdpTable.dwNumEntries; Row += 1)
                {
                    IntPtr TableOffset          = Marshal.OffsetOf(typeof(MIB_UDPTABLE_OWNER_PID), "table");
                    int    RowSize              = Marshal.SizeOf(typeof(MIB_UDPROW_OWNER_PID));
                    IntPtr RowOffset            = IntPtr.Add(TableOffset, (int)(RowSize * Row));
                    MIB_UDPROW_OWNER_PID UdpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(IntPtr.Add(Table, (int)RowOffset), typeof(MIB_UDPROW_OWNER_PID));

                    if (UdpRow.dwOwningPid != (uint)CurrentProcessId)
                    {
                        continue;
                    }

                    LocalPort = IPAddress.NetworkToHostOrder((short)UdpRow.dwLocalPort);

                    //
                    // Use loopback (disable deprecation warning) if we have no
                    // bound address.
                    //

#pragma warning disable 618
                    if (UdpRow.dwLocalAddr == 0)
                    {
                        UdpRow.dwLocalAddr = (uint)(ulong)IPAddress.Loopback.Address;
                    }
#pragma warning restore 618

                    //
                    // Cache the data and return a new endpoint object for the
                    // address.
                    //

                    Script.SetGlobalInt("ACR_SERVERLISTENER_PORT", LocalPort);
                    Script.SetGlobalInt("ACR_SERVERLISTENER_ADDRESS", (int)UdpRow.dwLocalAddr);

                    return(new IPEndPoint((long)(ulong)UdpRow.dwLocalAddr, LocalPort));
                }
            }
            finally
            {
                if (Table != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(Table);
                }
            }

            throw new ApplicationException("Endpoint not found.");
        }
Exemple #9
0
        /// <summary>
        /// This function reads and parses the active UDP socket connections available
        /// and stores them in a list.
        /// </summary>
        /// <returns>
        /// It returns the current set of UDP socket connections which are active.
        /// </returns>
        /// <exception cref="OutOfMemoryException">
        /// This exception may be thrown by the function Marshal.AllocHGlobal when there
        /// is insufficient memory to satisfy the request.
        /// </exception>
        private static List <UdpProcessRecord> GetAllUdpConnections()
        {
            int bufferSize = 0;
            List <UdpProcessRecord> udpTableRecords = new List <UdpProcessRecord>();

            // Getting the size of UDP table, that is returned in 'bufferSize' variable.
            uint result = GetExtendedUdpTable(IntPtr.Zero, ref bufferSize, true,
                                              AF_INET, UdpTableClass.UDP_TABLE_OWNER_PID);

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

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

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

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

                // Reading and parsing the UDP records one by one from the table and
                // storing them in a list of 'UdpProcessRecord' structure type objects.
                for (int i = 0; i < udpRecordsTable.dwNumEntries; i++)
                {
                    MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)
                                                  Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    udpTableRecords.Add(new UdpProcessRecord(new IPAddress(udpRow.localAddr),
                                                             BitConverter.ToUInt16(new byte[2] {
                        udpRow.localPort[1],
                        udpRow.localPort[0]
                    }, 0), udpRow.owningPid));
                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow));
                }
            }
            catch (OutOfMemoryException outOfMemoryException)
            {
                MessageBox.Show(outOfMemoryException.Message, "Out Of Memory",
                                MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Exception",
                                MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                Marshal.FreeHGlobal(udpTableRecordPtr);
            }
            return(udpTableRecords != null?udpTableRecords.Distinct()
                   .ToList <UdpProcessRecord>() : new List <UdpProcessRecord>());
        }
Exemple #10
0
        /// <summary>
        /// Add to list UDP connections using IPv4.
        /// </summary>
        /// <param name="table"></param>
        static void GetIPv4Info(MIB_UDPTABLE_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_UDPROW_OWNER_PID row = firstRow[i];
                SocketList.Add(new CSocket("UDP", row.dwLocalAddr, row.dwLocalPort, 0, 0, row.dwOwningPid, 0));
            }
        }
Exemple #11
0
        public static IEnumerable <UdpConnectionInfo> GetUdpConnections(IPVersion ipVersion, Dictionary <int, Process> processesByPid = null)
        {
            int bufferSize = 0;
            List <UdpConnectionInfo> udpTableRecords = new List <UdpConnectionInfo>();

            int ulAf = AF_INET;

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

            // Getting the initial size of UDP table.
            uint result = Iphlpapi.GetExtendedUdpTable(IntPtr.Zero, ref bufferSize, true, ulAf, UdpTableClass.UDP_TABLE_OWNER_PID);

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

            try
            {
                // The IntPtr from last call, udpTableRecoresPtr must be used in the subsequent
                // call and passed as the first parameter.
                result = Iphlpapi.GetExtendedUdpTable(udpTableRecordsPtr, ref bufferSize, true, ulAf, UdpTableClass.UDP_TABLE_OWNER_PID);

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

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

                // Determine if IPv4 or IPv6.
                if (ipVersion == IPVersion.IPv4)
                {
                    MIB_UDPTABLE_OWNER_PID udpRecordsTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDPTABLE_OWNER_PID));
                    IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries));

                    // Read and parse the UDP records from the table and store them in list
                    // 'UdpConnection' structure type objects.
                    for (int i = 0; i < udpRecordsTable.dwNumEntries; i++)
                    {
                        MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID));
                        udpTableRecords.Add(new UdpConnectionInfo(
                                                Protocol.UDP,
                                                new IPAddress(udpRow.localAddr),
                                                BitConverter.ToUInt16(new byte[2] {
                            udpRow.localPort[1],
                            udpRow.localPort[0]
                        }, 0),
                                                udpRow.owningPid,
                                                GetProcessNameByPid(udpRow.owningPid, processesByPid)));

                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow));
                    }
                }
                else if (ipVersion == IPVersion.IPv6)
                {
                    MIB_UDP6TABLE_OWNER_PID udpRecordsTable = (MIB_UDP6TABLE_OWNER_PID)
                                                              Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDP6TABLE_OWNER_PID));
                    IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr +
                                                  Marshal.SizeOf(udpRecordsTable.dwNumEntries));

                    // Read and parse the UDP records from the table and store them in list
                    // 'UdpConnection' structure type objects.
                    for (int i = 0; i < udpRecordsTable.dwNumEntries; i++)
                    {
                        MIB_UDP6ROW_OWNER_PID udpRow = (MIB_UDP6ROW_OWNER_PID)
                                                       Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDP6ROW_OWNER_PID));
                        udpTableRecords.Add(new UdpConnectionInfo(
                                                Protocol.UDP,
                                                new IPAddress(udpRow.localAddr, udpRow.localScopeId),
                                                BitConverter.ToUInt16(new byte[2] {
                            udpRow.localPort[1],
                            udpRow.localPort[0]
                        }, 0),
                                                udpRow.owningPid,
                                                GetProcessNameByPid(udpRow.owningPid, processesByPid)));
                        tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow));
                    }
                }
            }
            catch (OutOfMemoryException outOfMemoryException)
            {
                throw outOfMemoryException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                Marshal.FreeHGlobal(udpTableRecordsPtr);
            }

            return(udpTableRecords != null?udpTableRecords.Distinct().ToList() : new List <UdpConnectionInfo>());
        }