Beispiel #1
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);
        }