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

后端 未结 27 2339
感动是毒
感动是毒 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:18

    I personally find the answer of Anton and moffeltje best, but I added a check to exclude virtual networks set up by VMWare and others.

    public static bool IsAvailableNetworkActive()
    {
        // only recognizes changes related to Internet adapters
        if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) return false;
    
        // 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)
                where (!(face.Name.ToLower().Contains("virtual") || face.Description.ToLower().Contains("virtual")))
                select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
    }
    

提交回复
热议问题