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

后端 未结 27 2334
感动是毒
感动是毒 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 wouldn't think it's impossible, just not straightforward.

    I've built something like this, and yes it's not perfect, but the first step is essential: to check if there's any network connectivity. The Windows Api doesn't do a great job, so why not do a better job?

    bool NetworkIsAvailable()
    {
        var all = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
        foreach (var item in all)
        {
            if (item.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                continue;
            if (item.Name.ToLower().Contains("virtual") || item.Description.ToLower().Contains("virtual"))
                continue; //Exclude virtual networks set up by VMWare and others
            if (item.OperationalStatus == OperationalStatus.Up)
            {
                return true;
            }
        }
    
        return false;
    }
    

    It's pretty simple, but it really helps improve the quality of the check, especially when you want to check various proxy configurations.

    So:

    • Check whether there's network connectivity (make this really good, maybe even have logs sent back to developers when there are false positives to improve the NetworkIsAvailable function)
    • HTTP Ping
    • (Cycle through Proxy configurations with HTTP Pings on each)

提交回复
热议问题