internal static extern uint IcmpSendEcho2(SafeCloseIcmpHandle icmpHandle, IntPtr Event, IntPtr apcRoutine, IntPtr apcContext, uint ipAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
 internal static extern uint GetAdaptersAddresses(AddressFamily family, uint flags, IntPtr pReserved, SafeLocalFree adapterAddresses, ref uint outBufLen);
Ejemplo n.º 3
0
 internal static extern uint GetTcpTable2(SafeLocalFree pTcpTable, ref uint dwOutBufLen, bool order);
        private static SystemNetworkInterface[] PostWin2KGetNetworkInterfaces(AddressFamily family)
        {
            FixedInfo fixedInfo = SystemIPGlobalProperties.GetFixedInfo();

            SystemNetworkInterface[] adaptersAddresses = null;
Label_0008:
            try
            {
                adaptersAddresses = GetAdaptersAddresses(family, fixedInfo);
            }
            catch (NetworkInformationException exception)
            {
                if (exception.ErrorCode != 1L)
                {
                    throw;
                }
                goto Label_0008;
            }
            if (Socket.OSSupportsIPv4)
            {
                uint          pOutBufLen   = 0;
                uint          adaptersInfo = 0;
                SafeLocalFree pAdapterInfo = null;
                if ((family == AddressFamily.Unspecified) || (family == AddressFamily.InterNetwork))
                {
                    adaptersInfo = UnsafeNetInfoNativeMethods.GetAdaptersInfo(SafeLocalFree.Zero, ref pOutBufLen);
                    int num3 = 0;
                    while (adaptersInfo == 0x6f)
                    {
                        try
                        {
                            pAdapterInfo = SafeLocalFree.LocalAlloc((int)pOutBufLen);
                            adaptersInfo = UnsafeNetInfoNativeMethods.GetAdaptersInfo(pAdapterInfo, ref pOutBufLen);
                            if (adaptersInfo == 0)
                            {
                                IntPtr handle = pAdapterInfo.DangerousGetHandle();
                                while (handle != IntPtr.Zero)
                                {
                                    IpAdapterInfo ipAdapterInfo = (IpAdapterInfo)Marshal.PtrToStructure(handle, typeof(IpAdapterInfo));
                                    for (int i = 0; i < adaptersAddresses.Length; i++)
                                    {
                                        if ((adaptersAddresses[i] != null) && (ipAdapterInfo.index == adaptersAddresses[i].index))
                                        {
                                            if (!adaptersAddresses[i].interfaceProperties.Update(fixedInfo, ipAdapterInfo))
                                            {
                                                adaptersAddresses[i] = null;
                                                num3++;
                                            }
                                            break;
                                        }
                                    }
                                    handle = ipAdapterInfo.Next;
                                }
                            }
                            continue;
                        }
                        finally
                        {
                            if (pAdapterInfo != null)
                            {
                                pAdapterInfo.Close();
                            }
                        }
                    }
                    if (num3 != 0)
                    {
                        SystemNetworkInterface[] interfaceArray2 = new SystemNetworkInterface[adaptersAddresses.Length - num3];
                        int num5 = 0;
                        for (int j = 0; j < adaptersAddresses.Length; j++)
                        {
                            if (adaptersAddresses[j] != null)
                            {
                                interfaceArray2[num5++] = adaptersAddresses[j];
                            }
                        }
                        adaptersAddresses = interfaceArray2;
                    }
                }
                if ((adaptersInfo != 0) && (adaptersInfo != 0xe8))
                {
                    throw new NetworkInformationException((int)adaptersInfo);
                }
            }
            return(adaptersAddresses);
        }
        /// <summary>Gets the active udp listeners. Uses the native GetUdpTable api.</summary>
        public override IPEndPoint[] GetActiveUdpListeners()
        {
            uint              size         = 0;
            uint              result       = 0;
            SafeLocalFree     buffer       = null;
            List <IPEndPoint> udpListeners = new List <IPEndPoint>();

            // Check if it support IPv4 for IPv6 only modes.
            if (Socket.OSSupportsIPv4)
            {
                // Get the size of buffer needed
                result = UnsafeNetInfoNativeMethods.GetUdpTable(SafeLocalFree.Zero, ref size, true);
                while (result == IpHelperErrors.ErrorInsufficientBuffer)
                {
                    try {
                        //allocate the buffer and get the udptable
                        buffer = SafeLocalFree.LocalAlloc((int)size);
                        result = UnsafeNetInfoNativeMethods.GetUdpTable(buffer, ref size, true);

                        if (result == IpHelperErrors.Success)
                        {
                            //the table info just gives us the number of rows.
                            IntPtr      newPtr       = buffer.DangerousGetHandle();
                            MibUdpTable udpTableInfo = (MibUdpTable)Marshal.PtrToStructure(newPtr, typeof(MibUdpTable));

                            if (udpTableInfo.numberOfEntries > 0)
                            {
                                //we need to skip over the tableinfo to get the inline rows
                                newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(udpTableInfo.numberOfEntries));
                                for (int i = 0; i < udpTableInfo.numberOfEntries; i++)
                                {
                                    MibUdpRow udpRow    = (MibUdpRow)Marshal.PtrToStructure(newPtr, typeof(MibUdpRow));
                                    int       localPort = udpRow.localPort1 << 8 | udpRow.localPort2;

                                    udpListeners.Add(new IPEndPoint(udpRow.localAddr, (int)localPort));

                                    //we increment the pointer to the next row
                                    newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(udpRow));
                                }
                            }
                        }
                    }
                    finally {
                        if (buffer != null)
                        {
                            buffer.Close();
                        }
                    }
                }
                // if we don't have any ipv4 interfaces detected, just continue
                if (result != IpHelperErrors.Success && result != IpHelperErrors.ErrorNoData)
                {
                    throw new NetworkInformationException((int)result);
                }
            }

            if (Socket.OSSupportsIPv6)
            {
                // Get the size of buffer needed
                size   = 0;
                result = UnsafeNetInfoNativeMethods.GetExtendedUdpTable(SafeLocalFree.Zero, ref size, true,
                                                                        (uint)AddressFamily.InterNetworkV6,
                                                                        UdpTableClass.UdpTableOwnerPid, 0);
                while (result == IpHelperErrors.ErrorInsufficientBuffer)
                {
                    try {
                        // Allocate the buffer and get the udptable
                        buffer = SafeLocalFree.LocalAlloc((int)size);
                        result = UnsafeNetInfoNativeMethods.GetExtendedUdpTable(buffer, ref size, true,
                                                                                (uint)AddressFamily.InterNetworkV6,
                                                                                UdpTableClass.UdpTableOwnerPid, 0);

                        if (result == IpHelperErrors.Success)
                        {
                            // The table info just gives us the number of rows.
                            IntPtr newPtr = buffer.DangerousGetHandle();
                            MibUdp6TableOwnerPid udp6TableOwnerPid
                                = (MibUdp6TableOwnerPid)Marshal.PtrToStructure(newPtr, typeof(MibUdp6TableOwnerPid));

                            if (udp6TableOwnerPid.numberOfEntries > 0)
                            {
                                // We need to skip over the tableinfo to get the inline rows
                                newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(udp6TableOwnerPid.numberOfEntries));
                                for (int i = 0; i < udp6TableOwnerPid.numberOfEntries; i++)
                                {
                                    MibUdp6RowOwnerPid udp6RowOwnerPid
                                        = (MibUdp6RowOwnerPid)Marshal.PtrToStructure(newPtr,
                                                                                     typeof(MibUdp6RowOwnerPid));
                                    int localPort = udp6RowOwnerPid.localPort1 << 8 | udp6RowOwnerPid.localPort2;

                                    udpListeners.Add(new IPEndPoint(new IPAddress(udp6RowOwnerPid.localAddr,
                                                                                  udp6RowOwnerPid.localScopeId), localPort));

                                    // We increment the pointer to the next row
                                    newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(udp6RowOwnerPid));
                                }
                            }
                        }
                    }
                    finally {
                        if (buffer != null)
                        {
                            buffer.Close();
                        }
                    }
                }
                // If we don't have any ipv6 interfaces detected, just continue
                if (result != IpHelperErrors.Success && result != IpHelperErrors.ErrorNoData)
                {
                    throw new NetworkInformationException((int)result);
                }
            }

            return(udpListeners.ToArray());
        }
        internal static NetworkInterface[] GetNetworkInterfaces()
        {
            Contract.Ensures(Contract.Result <NetworkInterface[]>() != null);
            AddressFamily family     = AddressFamily.Unspecified;
            uint          bufferSize = 0;
            SafeLocalFree buffer     = null;
            FixedInfo     fixedInfo  = SystemIPGlobalProperties.GetFixedInfo();
            List <SystemNetworkInterface> interfaceList = new List <SystemNetworkInterface>();

            GetAdaptersAddressesFlags flags =
                GetAdaptersAddressesFlags.IncludeGateways
                | GetAdaptersAddressesFlags.IncludeWins;

            // Figure out the right buffer size for the adapter information
            uint result = UnsafeNetInfoNativeMethods.GetAdaptersAddresses(
                family, (uint)flags, IntPtr.Zero, SafeLocalFree.Zero, ref bufferSize);

            while (result == IpHelperErrors.ErrorBufferOverflow)
            {
                try {
                    // Allocate the buffer and get the adapter info
                    buffer = SafeLocalFree.LocalAlloc((int)bufferSize);
                    result = UnsafeNetInfoNativeMethods.GetAdaptersAddresses(
                        family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize);

                    // If succeeded, we're going to add each new interface
                    if (result == IpHelperErrors.Success)
                    {
                        // Linked list of interfaces
                        IntPtr ptr = buffer.DangerousGetHandle();
                        while (ptr != IntPtr.Zero)
                        {
                            // Traverse the list, marshal in the native structures, and create new NetworkInterfaces
                            IpAdapterAddresses adapterAddresses =
                                (IpAdapterAddresses)Marshal.PtrToStructure(ptr, typeof(IpAdapterAddresses));
                            interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses));

                            ptr = adapterAddresses.next;
                        }
                    }
                }
                finally {
                    if (buffer != null)
                    {
                        buffer.Close();
                    }
                    buffer = null;
                }
            }

            // if we don't have any interfaces detected, return empty.
            if (result == IpHelperErrors.ErrorNoData || result == IpHelperErrors.ErrorInvalidParameter)
            {
                return(new SystemNetworkInterface[0]);
            }

            // Otherwise we throw on an error
            if (result != IpHelperErrors.Success)
            {
                throw new NetworkInformationException((int)result);
            }

            return(interfaceList.ToArray());
        }
Ejemplo n.º 7
0
        // internal method responsible for sending echo request on win2k and higher

        private PingReply InternalSend(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool async)
        {
            ipv6     = (address.AddressFamily == AddressFamily.InterNetworkV6)?true:false;
            sendSize = buffer.Length;

            //get and cache correct handle
            if (!ipv6 && handlePingV4 == null)
            {
                handlePingV4 = UnsafeNetInfoNativeMethods.IcmpCreateFile();
                if (handlePingV4.IsInvalid)
                {
                    handlePingV4 = null;
                    throw new Win32Exception(); // Gets last error
                }
            }
            else if (ipv6 && handlePingV6 == null)
            {
                handlePingV6 = UnsafeNetInfoNativeMethods.Icmp6CreateFile();
                if (handlePingV6.IsInvalid)
                {
                    handlePingV6 = null;
                    throw new Win32Exception(); // Gets last error
                }
            }


            //setup the options
            IPOptions ipOptions = new IPOptions(options);

            //setup the reply buffer
            if (replyBuffer == null)
            {
                replyBuffer = SafeLocalFree.LocalAlloc(MaxUdpPacket);
            }

            //queue the event
            int error;

            try
            {
                if (async)
                {
                    if (pingEvent == null)
                    {
                        pingEvent = new ManualResetEvent(false);
                    }
                    else
                    {
                        pingEvent.Reset();
                    }

                    registeredWait = ThreadPool.RegisterWaitForSingleObject(pingEvent, new WaitOrTimerCallback(PingCallback), this, -1, true);
                }

                //Copy user dfata into the native world
                SetUnmanagedStructures(buffer);

                if (!ipv6)
                {
                    if (async)
                    {
                        error = (int)UnsafeNetInfoNativeMethods.IcmpSendEcho2(handlePingV4, pingEvent.SafeWaitHandle, IntPtr.Zero, IntPtr.Zero, (uint)address.m_Address, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                    else
                    {
                        error = (int)UnsafeNetInfoNativeMethods.IcmpSendEcho2(handlePingV4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, (uint)address.m_Address, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                }
                else
                {
                    IPEndPoint    ep         = new IPEndPoint(address, 0);
                    SocketAddress remoteAddr = ep.Serialize();
                    byte[]        sourceAddr = new byte[28];
                    if (async)
                    {
                        error = (int)UnsafeNetInfoNativeMethods.Icmp6SendEcho2(handlePingV6, pingEvent.SafeWaitHandle, IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.m_Buffer, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                    else
                    {
                        error = (int)UnsafeNetInfoNativeMethods.Icmp6SendEcho2(handlePingV6, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.m_Buffer, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                }
            }
            catch
            {
                UnregisterWaitHandle();
                throw;
            }

            //need this if something is bogus.
            if (error == 0)
            {
                error = (int)Marshal.GetLastWin32Error();

                // Only skip Async IO Pending error value
                if (async && error == UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
                {
                    return(null); // Expected async return value
                }
                // Cleanup
                FreeUnmanagedStructures();
                UnregisterWaitHandle();

                if (async || // No IPStatus async errors
                    error < (int)IPStatus.DestinationNetworkUnreachable || // Min
                    error > (int)IPStatus.DestinationScopeMismatch)    // Max // Out of IPStatus range
                {
                    throw new Win32Exception(error);
                }

                return(new PingReply((IPStatus)error)); // Synchronous IPStatus errors
            }

            if (async)
            {
                return(null);
            }

            FreeUnmanagedStructures();

            //return the reply
            PingReply reply;

            if (ipv6)
            {
                Icmp6EchoReply icmp6Reply = (Icmp6EchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(Icmp6EchoReply));
                reply = new PingReply(icmp6Reply, replyBuffer.DangerousGetHandle(), sendSize);
            }
            else
            {
                IcmpEchoReply icmpReply = (IcmpEchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(IcmpEchoReply));
                reply = new PingReply(icmpReply);
            }

            // IcmpEchoReply still has an unsafe IntPtr reference into replybuffer
            // and replybuffer was being freed prematurely by the GC, causing AccessViolationExceptions.
            GC.KeepAlive(replyBuffer);

            return(reply);
        }
Ejemplo n.º 8
0
 internal extern static uint GetExtendedUdpTable(SafeLocalFree pUdpTable, ref uint dwOutBufLen, bool order,
                                                 uint IPVersion, UdpTableClass tableClass, uint reserved);
        private List <SystemTcpConnectionInformation> GetAllTcpConnections()
        {
            uint          dwOutBufLen = 0;
            uint          num2        = 0;
            SafeLocalFree pTcpTable   = null;
            List <SystemTcpConnectionInformation> list = new List <SystemTcpConnectionInformation>();

            if (Socket.OSSupportsIPv4)
            {
                num2 = UnsafeNetInfoNativeMethods.GetTcpTable(SafeLocalFree.Zero, ref dwOutBufLen, true);
                while (num2 == 0x7a)
                {
                    try
                    {
                        pTcpTable = SafeLocalFree.LocalAlloc((int)dwOutBufLen);
                        num2      = UnsafeNetInfoNativeMethods.GetTcpTable(pTcpTable, ref dwOutBufLen, true);
                        if (num2 == 0)
                        {
                            IntPtr      handle = pTcpTable.DangerousGetHandle();
                            MibTcpTable table  = (MibTcpTable)Marshal.PtrToStructure(handle, typeof(MibTcpTable));
                            if (table.numberOfEntries > 0)
                            {
                                handle = (IntPtr)(((long)handle) + Marshal.SizeOf(table.numberOfEntries));
                                for (int i = 0; i < table.numberOfEntries; i++)
                                {
                                    MibTcpRow row = (MibTcpRow)Marshal.PtrToStructure(handle, typeof(MibTcpRow));
                                    list.Add(new SystemTcpConnectionInformation(row));
                                    handle = (IntPtr)(((long)handle) + Marshal.SizeOf(row));
                                }
                            }
                        }
                        continue;
                    }
                    finally
                    {
                        if (pTcpTable != null)
                        {
                            pTcpTable.Close();
                        }
                    }
                }
                if ((num2 != 0) && (num2 != 0xe8))
                {
                    throw new NetworkInformationException((int)num2);
                }
            }
            if (Socket.OSSupportsIPv6)
            {
                dwOutBufLen = 0;
                num2        = UnsafeNetInfoNativeMethods.GetExtendedTcpTable(SafeLocalFree.Zero, ref dwOutBufLen, true, 0x17, TcpTableClass.TcpTableOwnerPidAll, 0);
                while (num2 == 0x7a)
                {
                    try
                    {
                        pTcpTable = SafeLocalFree.LocalAlloc((int)dwOutBufLen);
                        num2      = UnsafeNetInfoNativeMethods.GetExtendedTcpTable(pTcpTable, ref dwOutBufLen, true, 0x17, TcpTableClass.TcpTableOwnerPidAll, 0);
                        if (num2 == 0)
                        {
                            IntPtr ptr = pTcpTable.DangerousGetHandle();
                            MibTcp6TableOwnerPid pid = (MibTcp6TableOwnerPid)Marshal.PtrToStructure(ptr, typeof(MibTcp6TableOwnerPid));
                            if (pid.numberOfEntries > 0)
                            {
                                ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(pid.numberOfEntries));
                                for (int j = 0; j < pid.numberOfEntries; j++)
                                {
                                    MibTcp6RowOwnerPid pid2 = (MibTcp6RowOwnerPid)Marshal.PtrToStructure(ptr, typeof(MibTcp6RowOwnerPid));
                                    list.Add(new SystemTcpConnectionInformation(pid2));
                                    ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(pid2));
                                }
                            }
                        }
                        continue;
                    }
                    finally
                    {
                        if (pTcpTable != null)
                        {
                            pTcpTable.Close();
                        }
                    }
                }
                if ((num2 != 0) && (num2 != 0xe8))
                {
                    throw new NetworkInformationException((int)num2);
                }
            }
            return(list);
        }
        public override IPEndPoint[] GetActiveUdpListeners()
        {
            uint              dwOutBufLen = 0;
            uint              num2        = 0;
            SafeLocalFree     pUdpTable   = null;
            List <IPEndPoint> list        = new List <IPEndPoint>();

            if (Socket.OSSupportsIPv4)
            {
                num2 = UnsafeNetInfoNativeMethods.GetUdpTable(SafeLocalFree.Zero, ref dwOutBufLen, true);
                while (num2 == 0x7a)
                {
                    try
                    {
                        pUdpTable = SafeLocalFree.LocalAlloc((int)dwOutBufLen);
                        num2      = UnsafeNetInfoNativeMethods.GetUdpTable(pUdpTable, ref dwOutBufLen, true);
                        if (num2 == 0)
                        {
                            IntPtr      handle = pUdpTable.DangerousGetHandle();
                            MibUdpTable table  = (MibUdpTable)Marshal.PtrToStructure(handle, typeof(MibUdpTable));
                            if (table.numberOfEntries > 0)
                            {
                                handle = (IntPtr)(((long)handle) + Marshal.SizeOf(table.numberOfEntries));
                                for (int i = 0; i < table.numberOfEntries; i++)
                                {
                                    MibUdpRow structure = (MibUdpRow)Marshal.PtrToStructure(handle, typeof(MibUdpRow));
                                    int       port      = (structure.localPort1 << 8) | structure.localPort2;
                                    list.Add(new IPEndPoint((long)structure.localAddr, port));
                                    handle = (IntPtr)(((long)handle) + Marshal.SizeOf(structure));
                                }
                            }
                        }
                        continue;
                    }
                    finally
                    {
                        if (pUdpTable != null)
                        {
                            pUdpTable.Close();
                        }
                    }
                }
                if ((num2 != 0) && (num2 != 0xe8))
                {
                    throw new NetworkInformationException((int)num2);
                }
            }
            if (Socket.OSSupportsIPv6)
            {
                dwOutBufLen = 0;
                num2        = UnsafeNetInfoNativeMethods.GetExtendedUdpTable(SafeLocalFree.Zero, ref dwOutBufLen, true, 0x17, UdpTableClass.UdpTableOwnerPid, 0);
                while (num2 == 0x7a)
                {
                    try
                    {
                        pUdpTable = SafeLocalFree.LocalAlloc((int)dwOutBufLen);
                        num2      = UnsafeNetInfoNativeMethods.GetExtendedUdpTable(pUdpTable, ref dwOutBufLen, true, 0x17, UdpTableClass.UdpTableOwnerPid, 0);
                        if (num2 == 0)
                        {
                            IntPtr ptr = pUdpTable.DangerousGetHandle();
                            MibUdp6TableOwnerPid pid = (MibUdp6TableOwnerPid)Marshal.PtrToStructure(ptr, typeof(MibUdp6TableOwnerPid));
                            if (pid.numberOfEntries > 0)
                            {
                                ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(pid.numberOfEntries));
                                for (int j = 0; j < pid.numberOfEntries; j++)
                                {
                                    MibUdp6RowOwnerPid pid2 = (MibUdp6RowOwnerPid)Marshal.PtrToStructure(ptr, typeof(MibUdp6RowOwnerPid));
                                    int num6 = (pid2.localPort1 << 8) | pid2.localPort2;
                                    list.Add(new IPEndPoint(new IPAddress(pid2.localAddr, (long)pid2.localScopeId), num6));
                                    ptr = (IntPtr)(((long)ptr) + Marshal.SizeOf(pid2));
                                }
                            }
                        }
                        continue;
                    }
                    finally
                    {
                        if (pUdpTable != null)
                        {
                            pUdpTable.Close();
                        }
                    }
                }
                if ((num2 != 0) && (num2 != 0xe8))
                {
                    throw new NetworkInformationException((int)num2);
                }
            }
            return(list.ToArray());
        }
Ejemplo n.º 11
0
 internal extern static uint Icmp6SendEcho2(SafeCloseIcmpHandle icmpHandle, IntPtr Event, IntPtr apcRoutine, IntPtr apcContext,
                                            byte[] sourceSocketAddress, byte[] destSocketAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
Ejemplo n.º 12
0
 internal extern static uint GetPerAdapterInfo(uint IfIndex, SafeLocalFree pPerAdapterInfo, ref uint pOutBufLen);
Ejemplo n.º 13
0
 internal extern static uint GetNetworkParams(SafeLocalFree pFixedInfo, ref uint pOutBufLen);
 internal static extern uint GetAdaptersInfo(SafeLocalFree pAdapterInfo, ref uint pOutBufLen);
        /// <summary>
        /// Gets the active tcp connections. Uses the native GetTcpTable api.</summary>
        private List <SystemTcpConnectionInformation> GetAllTcpConnections()
        {
            uint          size   = 0;
            uint          result = 0;
            SafeLocalFree buffer = null;
            List <SystemTcpConnectionInformation> tcpConnections = new List <SystemTcpConnectionInformation>();

            // Check if it supports IPv4 for IPv6 only modes.
            if (Socket.OSSupportsIPv4)
            {
                // Get the size of buffer needed
                result = UnsafeNetInfoNativeMethods.GetTcpTable(SafeLocalFree.Zero, ref size, true);

                while (result == IpHelperErrors.ErrorInsufficientBuffer)
                {
                    try {
                        //allocate the buffer and get the tcptable
                        buffer = SafeLocalFree.LocalAlloc((int)size);
                        result = UnsafeNetInfoNativeMethods.GetTcpTable(buffer, ref size, true);

                        if (result == IpHelperErrors.Success)
                        {
                            //the table info just gives us the number of rows.
                            IntPtr      newPtr       = buffer.DangerousGetHandle();
                            MibTcpTable tcpTableInfo = (MibTcpTable)Marshal.PtrToStructure(newPtr, typeof(MibTcpTable));

                            if (tcpTableInfo.numberOfEntries > 0)
                            {
                                //we need to skip over the tableinfo to get the inline rows
                                newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(tcpTableInfo.numberOfEntries));

                                for (int i = 0; i < tcpTableInfo.numberOfEntries; i++)
                                {
                                    MibTcpRow tcpRow = (MibTcpRow)Marshal.PtrToStructure(newPtr, typeof(MibTcpRow));
                                    tcpConnections.Add(new SystemTcpConnectionInformation(tcpRow));

                                    //we increment the pointer to the next row
                                    newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(tcpRow));
                                }
                            }
                        }
                    }
                    finally {
                        if (buffer != null)
                        {
                            buffer.Close();
                        }
                    }
                }

                // if we don't have any ipv4 interfaces detected, just continue
                if (result != IpHelperErrors.Success && result != IpHelperErrors.ErrorNoData)
                {
                    throw new NetworkInformationException((int)result);
                }
            }

            if (Socket.OSSupportsIPv6)
            {
                // IPv6 tcp connections
                // Get the size of buffer needed
                size   = 0;
                result = UnsafeNetInfoNativeMethods.GetExtendedTcpTable(SafeLocalFree.Zero, ref size, true,
                                                                        (uint)AddressFamily.InterNetworkV6,
                                                                        TcpTableClass.TcpTableOwnerPidAll, 0);

                while (result == IpHelperErrors.ErrorInsufficientBuffer)
                {
                    try {
                        // Allocate the buffer and get the tcptable
                        buffer = SafeLocalFree.LocalAlloc((int)size);
                        result = UnsafeNetInfoNativeMethods.GetExtendedTcpTable(buffer, ref size, true,
                                                                                (uint)AddressFamily.InterNetworkV6,
                                                                                TcpTableClass.TcpTableOwnerPidAll, 0);
                        if (result == IpHelperErrors.Success)
                        {
                            // The table info just gives us the number of rows.
                            IntPtr newPtr = buffer.DangerousGetHandle();

                            MibTcp6TableOwnerPid tcpTable6OwnerPid
                                = (MibTcp6TableOwnerPid)Marshal.PtrToStructure(newPtr, typeof(MibTcp6TableOwnerPid));

                            if (tcpTable6OwnerPid.numberOfEntries > 0)
                            {
                                // We need to skip over the tableinfo to get the inline rows
                                newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(tcpTable6OwnerPid.numberOfEntries));

                                for (int i = 0; i < tcpTable6OwnerPid.numberOfEntries; i++)
                                {
                                    MibTcp6RowOwnerPid tcp6RowOwnerPid
                                        = (MibTcp6RowOwnerPid)Marshal.PtrToStructure(newPtr,
                                                                                     typeof(MibTcp6RowOwnerPid));
                                    tcpConnections.Add(new SystemTcpConnectionInformation(tcp6RowOwnerPid));

                                    // We increment the pointer to the next row
                                    newPtr = (IntPtr)((long)newPtr + Marshal.SizeOf(tcp6RowOwnerPid));
                                }
                            }
                        }
                    }
                    finally {
                        if (buffer != null)
                        {
                            buffer.Close();
                        }
                    }
                }

                // If we don't have any ipv6 interfaces detected, just continue
                if (result != IpHelperErrors.Success && result != IpHelperErrors.ErrorNoData)
                {
                    throw new NetworkInformationException((int)result);
                }
            }

            return(tcpConnections);
        }
 internal static extern uint GetExtendedTcpTable(SafeLocalFree pTcpTable, ref uint dwOutBufLen, bool order, uint IPVersion, TcpTableClass tableClass, uint reserved);
Ejemplo n.º 17
0
 internal extern static uint GetUdpTable(SafeLocalFree pUdpTable, ref uint dwOutBufLen, bool order);