Exemplo n.º 1
0
        private static IPAddress[] GetLocalAddresses()
        {
            IPAddress[] local;

            ArrayList collections = new ArrayList(16);
            int       total       = 0;

            SafeLocalFree             buffer   = null;
            GetAdaptersAddressesFlags gaaFlags = GetAdaptersAddressesFlags.SkipAnycast | GetAdaptersAddressesFlags.SkipMulticast |
                                                 GetAdaptersAddressesFlags.SkipFriendlyName | GetAdaptersAddressesFlags.SkipDnsServer;
            uint size   = 0;
            uint result = UnsafeNetInfoNativeMethods.GetAdaptersAddresses(AddressFamily.Unspecified, (uint)gaaFlags, IntPtr.Zero, SafeLocalFree.Zero, ref size);

            while (result == IpHelperErrors.ErrorBufferOverflow)
            {
                try
                {
                    buffer = SafeLocalFree.LocalAlloc((int)size);
                    result = UnsafeNetInfoNativeMethods.GetAdaptersAddresses(AddressFamily.Unspecified, (uint)gaaFlags, IntPtr.Zero, buffer, ref size);

                    if (result == IpHelperErrors.Success)
                    {
                        IntPtr nextAdapter = buffer.DangerousGetHandle();

                        while (nextAdapter != IntPtr.Zero)
                        {
                            IpAdapterAddresses adapterAddresses = (IpAdapterAddresses)Marshal.PtrToStructure(
                                nextAdapter, typeof(IpAdapterAddresses));

                            if (adapterAddresses.firstUnicastAddress != IntPtr.Zero)
                            {
                                UnicastIPAddressInformationCollection coll =
                                    SystemUnicastIPAddressInformation.MarshalUnicastIpAddressInformationCollection(
                                        adapterAddresses.firstUnicastAddress);
                                total += coll.Count;
                                collections.Add(coll);
                            }

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

            if (result != IpHelperErrors.Success && result != IpHelperErrors.ErrorNoData)
            {
                throw new NetworkInformationException((int)result);
            }

            local = new IPAddress[total];
            uint i = 0;

            foreach (UnicastIPAddressInformationCollection coll in collections)
            {
                foreach (IPAddressInformation info in coll)
                {
                    local[i++] = info.Address;
                }
            }

            return(local);
        }