private static IPAddress LoadIPAddress()
        {
            var interfaces = GetNetworkInterfaces();
            Func <IEnumerable <NetworkInterfaceData>, IEnumerable <IPAddress> > getAddresses = interfaceList =>
                                                                                               interfaceList.SelectMany(x => x.Addresses)
                                                                                               .OrderBy(x => x.AddressFamily != AddressFamily.InterNetwork); // Prefer IPv4 until working IPv6 detection is reliable

            // Even though the docs say that NetworkIntereface.Type only returns a subset of these types, I've seen some others
            // (for example Tunnel) in the wild, so let's just list all acceptable types.
            var preferedTypes = new NetworkInterfaceType[] {
                NetworkInterfaceType.Ethernet,
                NetworkInterfaceType.FastEthernetFx,
                NetworkInterfaceType.FastEthernetT,
                NetworkInterfaceType.GigabitEthernet,
            };
            var lanAddresses = getAddresses(interfaces.Where(x => preferedTypes.Contains(x.Type)));

            if (lanAddresses.Any())
            {
                return(lanAddresses.First());
            }

            var addresses = getAddresses(interfaces);

            if (addresses.Any(x => !_localhostNames.Contains(x.ToString())))
            {
                return(addresses.First(x => !_localhostNames.Contains(x.ToString())));
            }
            if (addresses.Any())
            {
                return(addresses.First());
            }

            return(IPAddress.Parse("127.0.0.1"));
        }
示例#2
0
        /* Returns an array of valid network interfaces.
        ** Used to create a NetworkMonitor object for
        ** all up and running network interfaces.
        ** Valid interfaces are those that are not a
        ** loopback or tunnel interface/adapter and
        ** are up and running and not a virtual ethernet
        ** interface/adapter. */
        private static NetworkInterface[] GetInterfaces()
        {
            // Unallowed interface types.
            var invalidInterfaces = new NetworkInterfaceType[2] {
                NetworkInterfaceType.Loopback,
                NetworkInterfaceType.Tunnel
            };

            // Store all interfaces.
            var interfaces = NetworkInterface.GetAllNetworkInterfaces();
            // Stores all valid interfaces.
            var validInterfaces = new List <NetworkInterface>();

            foreach (var intf in interfaces)
            {
                if (!(invalidInterfaces.Contains(intf.NetworkInterfaceType)))
                {
                    if (OperationalStatus.Up == intf.OperationalStatus &&
                        !(intf.Name.StartsWith("vEthernet")))
                    {
                        validInterfaces.Add(intf);
                    } /* Check if running and not virtual ethernet. */
                }     /* Check for valid interface type. */
            }         /* Loop through available interfaces. */
            return(validInterfaces.ToArray());
        }
        /// <summary>
        /// Inspects the local system for local (non-routable) IPv4 addresses.
        /// </summary>
        /// <returns>An IEnumerable of discovered local addresses.</returns>
        internal static IEnumerable <string> GetLocalIpAddresses()
        {
            List <string> addressList = new List <string>();

            NetworkInterfaceType[]         allowableTypes = new NetworkInterfaceType[] { NetworkInterfaceType.Ethernet, NetworkInterfaceType.Wireless80211, NetworkInterfaceType.GigabitEthernet };
            Tuple <IPAddress, IPAddress>[] privateRanges  = new Tuple <IPAddress, IPAddress>[]
            {
                Tuple.Create(IPAddress.Parse("10.0.0.0"), IPAddress.Parse("255.0.0.0")),
                Tuple.Create(IPAddress.Parse("172.16.0.0"), IPAddress.Parse("255.240.0.0")),
                Tuple.Create(IPAddress.Parse("192.168.0.0"), IPAddress.Parse("255.255.0.0")),
            };

            IEnumerable <NetworkInterface> interfaces = NetworkInterface.GetAllNetworkInterfaces()
                                                        .Where(i => i.OperationalStatus == OperationalStatus.Up)
                                                        .Where(i => allowableTypes.Contains(i.NetworkInterfaceType));

            foreach (NetworkInterface iface in interfaces)
            {
                var ifAddressInfo = iface.GetIPProperties().UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork);
                foreach (UnicastIPAddressInformation ifAddress in ifAddressInfo)
                {
                    IPAddress address = ifAddress.Address;
                    foreach (var range in privateRanges)
                    {
                        if (address.GetNetworkAddress(range.Item2).Equals(range.Item1))
                        {
                            addressList.Add(address.ToString());
                        }
                    }
                }
            }

            return(addressList);
        }
示例#4
0
        public static bool IsNetworkAvailable(string excludeIps = null)
        {
            // If no adapters available then return false;
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return(false);
            }
            var nics       = NetworkInterface.GetAllNetworkInterfaces();
            var badTypes   = new NetworkInterfaceType[] { NetworkInterfaceType.Tunnel, NetworkInterfaceType.Loopback };
            var goodFamily = new AddressFamily[] { AddressFamily.InterNetwork, AddressFamily.InterNetworkV6 };

            foreach (var nic in nics)
            {
                // If network interface is not up then skip.
                if (nic.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }
                // If interface type is invalid then skip.
                if (badTypes.Contains(nic.NetworkInterfaceType))
                {
                    continue;
                }
                // Get IP4 and IP6 statistics.
                //var stats = nic.GetIPStatistics();
                // If no data send or received then skip.
                //if (stats.BytesSent == 0 || stats.BytesReceived == 0)
                //	continue;
                // Loop trough IP address properties.
                var properties = nic.GetIPProperties();
                for (var a = 0; a < properties.UnicastAddresses.Count; a++)
                {
                    var address = properties.UnicastAddresses[a].Address;
                    // If not IP4 or IP6 then continue.
                    if (!goodFamily.Contains(address.AddressFamily))
                    {
                        continue;
                    }
                    // If loop back then continue.
                    if (IPAddress.IsLoopback(address))
                    {
                        continue;
                    }
                    // If excluded IP then continue.
                    if (excludeIps != null && IsExcludedIp(address.ToString(), excludeIps))
                    {
                        continue;
                    }
                    // Address passed availability.
                    return(true);
                }
            }
            return(false);
        }
示例#5
0
        /// <summary>
        /// This method is time consuming and would freeze application if you run it on main thread.
        /// </summary>
        public static NetworkInfo CheckNetwork(string excludeIps = null)
        {
            var info     = new NetworkInfo();
            var nicsList = new List <String>();
            var nics     = NetworkInterface.GetAllNetworkInterfaces();
            var ips      = new List <KeyValuePair <string, int> >();
            var badTypes = new NetworkInterfaceType[] { NetworkInterfaceType.Tunnel, NetworkInterfaceType.Loopback };

            for (int i = 0; i < nics.Length; i++)
            {
                var ni = nics[i];
                if (badTypes.Contains(ni.NetworkInterfaceType))
                {
                    continue;
                }
                var nicsSb = new StringBuilder();
                nicsSb.AppendFormat("    Name = {0}, Status = {1}", ni.Name, ni.OperationalStatus);
                var sb         = new StringBuilder();
                var properties = ni.GetIPProperties();
                FillAdapter(sb, ni);
                info.NicInfo.Add(new KeyValue(ni.Description, sb.ToString()));
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    var desc = ni.Description;
                    // If state is still off then...
                    if (!info.IsMobileNicUp)
                    {
                        info.IsMobileNicUp = desc.Contains("HSPA Network");
                    }
                    // If state is still off then...
                    if (!info.IsWirelessNicUp)
                    {
                        info.IsWirelessNicUp = desc.Contains("802.11") || desc.Contains("802.11");
                    }
                    // Loop trough IP address properties.
                    for (var a = 0; a < properties.UnicastAddresses.Count; a++)
                    {
                        var address = properties.UnicastAddresses[a].Address;
                        // If not IP4 version then skip.
                        if (address.AddressFamily != AddressFamily.InterNetwork)
                        {
                            continue;
                        }
                        // If loop-back then skip.
                        if (IPAddress.IsLoopback(address))
                        {
                            continue;
                        }
                        nicsSb.AppendFormat(", Address = {0}", address);
                        // If excluded then skip.
                        if (excludeIps != null && IsExcludedIp(address.ToString(), excludeIps))
                        {
                            continue;
                        }
                        // Normal IP4 address was found.
                        info.IsNetworkAvailable = true;
                        // More configuration = higher priority of IP address.
                        var priority =
                            properties.GatewayAddresses.Count +
                            properties.DnsAddresses.Count +
                            properties.DhcpServerAddresses.Count +
                            properties.WinsServersAddresses.Count;
                        ips.Add(new KeyValuePair <string, int>(address.ToString(), priority));
                    }
                }
                nicsList.Add(nicsSb.ToString());
            }
            info.CurrentNicks = string.Join("\r\n", nicsList);
            var ipAddress = ips.OrderByDescending(x => x.Value).Select(x => x.Key).FirstOrDefault();

            if (ipAddress != null)
            {
                info.LocalIpAddress = ipAddress;
            }
            return(info);
        }
        private static IPAddress LoadIPAddress()
        {
            var interfaces = GetNetworkInterfaces();
            Func<IEnumerable<NetworkInterfaceData>, IEnumerable<IPAddress>> getAddresses = interfaceList =>
                interfaceList.SelectMany(x => x.Addresses)
                             .OrderBy(x => x.AddressFamily != AddressFamily.InterNetwork); // Prefer IPv4 until working IPv6 detection is reliable

            // Even though the docs say that NetworkIntereface.Type only returns a subset of these types, I've seen some others
            // (for example Tunnel) in the wild, so let's just list all acceptable types.
            var preferedTypes = new NetworkInterfaceType[] {
                NetworkInterfaceType.Ethernet,
                NetworkInterfaceType.FastEthernetFx,
                NetworkInterfaceType.FastEthernetT,
                NetworkInterfaceType.GigabitEthernet,
            };
            var lanAddresses = getAddresses(interfaces.Where(x => preferedTypes.Contains(x.Type)));
            if (lanAddresses.Any())
                return lanAddresses.First();

            var addresses = getAddresses(interfaces);
            if (addresses.Any(x => !_localhostNames.Contains(x.ToString())))
                return addresses.First(x => !_localhostNames.Contains(x.ToString()));
            if (addresses.Any())
                return addresses.First();

            return IPAddress.Parse("127.0.0.1");
        }