What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2359
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

27条回答
  •  日久生厌
    2020-11-22 08:40

    Does not solve the problem of network going down between checking and running your code but is fairly reliable

    public static bool IsAvailableNetworkActive()
    {
        // only recognizes changes related to Internet adapters
        if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
        {
            // however, this will include all adapters -- filter by opstatus and activity
            NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            return (from face in interfaces
                    where face.OperationalStatus == OperationalStatus.Up
                    where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                    select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
        }
    
        return false;
    }
    

提交回复
热议问题