Beispiel #1
0
        public static MIB_UDPROW_OWNER_PID[] GetUdpTable()
        {
            MIB_UDPROW_OWNER_PID[] Entries = null;

            System.IntPtr Table = System.Runtime.InteropServices.Marshal.AllocHGlobal(5000);
            System.UInt32 Size  = 5000;

            System.UInt32 ret = GetExtendedUdpTable(Table, ref Size, false, Address_Family.AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
            if (ret == 0)
            {
                System.UInt32 NumEntries = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.ReadInt32(Table));
                System.IntPtr PtrEntries = AddToPointer(Table, 4);

                Entries = new MIB_UDPROW_OWNER_PID[NumEntries];
                for (int i = 0; i < NumEntries; ++i)
                {
                    Entries[i] = new MIB_UDPROW_OWNER_PID();

                    System.IntPtr PtrEntry = AddToPointer(PtrEntries, (i * System.Runtime.InteropServices.Marshal.SizeOf(Entries[i])));
                    System.Runtime.InteropServices.Marshal.PtrToStructure(PtrEntry, Entries[i]);
                }
            }
            System.Runtime.InteropServices.Marshal.FreeHGlobal(Table);
            return(Entries);
        }
Beispiel #2
0
        private static MIB_UDPROW_OWNER_PID[] _GetAllConnections()
        {
            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(null);
                }

                var    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++)
                {
                    var tcpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    tTable[i] = tcpRow;
                    rowPtr    = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry
                }
            } finally
            {
                Marshal.FreeHGlobal(buffTable);
            }
            return(tTable);
        }
        //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);
        }
Beispiel #4
0
        public static IEnumerable <ActiveConnectionDto> GetUdpConnections(int processId)
        {
            MIB_UDPROW_OWNER_PID[] tTable;
            var AF_INET  = 2; // IP_v4
            var buffSize = 0;

            // how much memory do we need?
            var ret = NativeMethods.GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);

            if (ret != 0 && ret != 122) // 122 insufficient buffer size
            {
                throw new Exception("bad ret on check " + ret);
            }

            var buffTable = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = NativeMethods.GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
                if (ret != 0)
                {
                    throw new Exception("bad ret " + ret);
                }

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

                for (var i = 0; i < tab.dwNumEntries; i++)
                {
                    var udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    tTable[i] = udpRow;
                    // next entry
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(udpRow));
                }
            }
            finally
            {
                // Free the Memory
                Marshal.FreeHGlobal(buffTable);
            }

            return(tTable.Where(x => x.owningPid == processId).Select(x => new ActiveConnectionDto
            {
                ProtocolName = ProtocolName.Udp,
                LocalAddress = IntToIp(x.localAddr),
                LocalPort = x.LocalPort,
                RemoteAddress = IntToIp(x.remoteAddr),
                RemotePort = x.RemotePort,
                State = ConnectionState.NoError
            }));
        }
        //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);
        }
Beispiel #6
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>());
        }
Beispiel #7
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);
        }
Beispiel #8
0
        private static List <int> GetArmaServerPorts()
        {
            List <int> ports       = new List <int>();
            int        bufferSize  = 0;
            uint       ret         = GetExtendedUdpTable(IntPtr.Zero, ref bufferSize, false, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
            IntPtr     bufferTable = Marshal.AllocHGlobal(bufferSize);

            try
            {
                ret = GetExtendedUdpTable(bufferTable, ref bufferSize, false, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                if (ret != 0)
                {
                    return(ports);
                }

                int    numberOfEntires = Marshal.ReadInt32(bufferTable, 0);
                IntPtr rowPtr          = bufferTable + 4;

                for (int i = 0; i < numberOfEntires; i++)
                {
                    MIB_UDPROW_OWNER_PID row = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    rowPtr = rowPtr + Marshal.SizeOf(row);

                    if (row.PID == Process.GetCurrentProcess().Id&& row.LocalAddress == 0)
                    {
                        ports.Add(row.LocalPort);
                    }
                }
            }
            finally
            {
                Marshal.FreeHGlobal(bufferTable);
            }

            return(ports);
        }
Beispiel #9
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.");
        }
        public static MIB_UDPROW_OWNER_PID[] GetUdpTable()
        {
            MIB_UDPROW_OWNER_PID[] Entries = null;

            System.IntPtr Table = System.Runtime.InteropServices.Marshal.AllocHGlobal(5000);
            System.UInt32 Size = 5000;

            System.UInt32 ret = GetExtendedUdpTable(Table, ref Size, false, Address_Family.AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
            if (ret == 0)
            {
                System.UInt32 NumEntries = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.ReadInt32(Table));
                System.IntPtr PtrEntries = AddToPointer(Table, 4);

                Entries = new MIB_UDPROW_OWNER_PID[NumEntries];
                for (int i = 0; i < NumEntries; ++i)
                {
                    Entries[i] = new MIB_UDPROW_OWNER_PID();

                    System.IntPtr PtrEntry = AddToPointer(PtrEntries, (i * System.Runtime.InteropServices.Marshal.SizeOf(Entries[i])));
                    System.Runtime.InteropServices.Marshal.PtrToStructure(PtrEntry, Entries[i]);
                }
            }
            System.Runtime.InteropServices.Marshal.FreeHGlobal(Table);
            return Entries;
        }
Beispiel #11
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>());
        }
Beispiel #12
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>());
        }