在。net中检查Internet连接的最快和最有效的方法是什么?


当前回答

以下是它在Android中的实现方式。

作为概念的证明,我将这段代码翻译成c#:

var request = (HttpWebRequest)WebRequest.Create("http://g.cn/generate_204");
request.UserAgent = "Android";
request.KeepAlive = false;
request.Timeout = 1500;

using (var response = (HttpWebResponse)request.GetResponse())
{
    if (response.ContentLength == 0 && response.StatusCode == HttpStatusCode.NoContent)
    {
        //Connection to internet available
    }
    else
    {
        //Connection to internet not available
    }
}

其他回答

我不认为这是不可能的,只是不简单。

我已经建立了这样的东西,是的,它并不完美,但第一步是必不可少的:检查是否有任何网络连接。Windows Api做得不好,为什么不做得更好呢?

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;
}

这非常简单,但它确实有助于提高检查的质量,特别是当您想检查各种代理配置时。

So:

检查是否有网络连接(让这真的很好,甚至可以在出现误报时将日志发送给开发人员,以改进NetworkIsAvailable功能) HTTP平 (循环代理配置,在每个代理上使用HTTP ping)

我已经看到了上面列出的所有选项,唯一可行的选项来检查互联网是否可用是“Ping”选项。 导入[DllImport("Wininet.dll")]和System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()或NetworkInterface类的任何其他变体都不能很好地检测网络的可用性。这些方法只检查网线是否插好。

“Ping选项”

if(Connection is available)返回true

if(连接不可用且网线已插入)返回false

if(网线未插入)抛出异常

的NetworkInterface

if(Internet可用)返回True

if(Internet不可用且网线已插入)返回True

if(Network Cable is Not plug in)返回false

[DllImport杂志》(“Wininet等”)。

if(Internet可用)返回True

if(Internet不可用且网线已插入)返回True

if(Network Cable is Not plug in)返回false

因此,在[DllImport("Wininet.dll")]和NetworkInterface的情况下,没有办法知道互联网连接是否可用。

private bool ping()
{
    System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
    System.Net.NetworkInformation.PingReply reply = pingSender.Send(address);
    if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
    {                
        return true;
    }
    else
    {                
        return false;
    }
}
public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
    try
    {
        url ??= CultureInfo.InstalledUICulture switch
        {
            { Name: var n } when n.StartsWith("fa") => // Iran
                "http://www.aparat.com",
            { Name: var n } when n.StartsWith("zh") => // China
                "http://www.baidu.com",
            _ =>
                "http://www.gstatic.com/generate_204",
        };

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = false;
        request.Timeout = timeoutMs;
        using (var response = (HttpWebResponse)request.GetResponse())
            return true;
    }
    catch
    {
        return false;
    }
}

我个人觉得Anton和moffeltje的答案最好,但我增加了一个检查,排除VMWare和其他公司设置的虚拟网络。

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));
}