为什么GetIsNetworkAvailable()总是返回true? [英] Why is GetIsNetworkAvailable() always returning true?

查看:1144
本文介绍了为什么GetIsNetworkAvailable()总是返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的方法:

public static void testConnection()
    {
        if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
        {
            System.Windows.MessageBox.Show("This computer is connected to the internet");
        }
        else
        {
            System.Windows.MessageBox.Show("This computer is not connected to the internet");
        }
    }



我想这会告诉我的连接是否可用或没有,但它总是返回true(并打印第1个消息),即使我敢肯定,没有任何连接。我做错了。

I suppose it would tell me whether the connection is available or not but it always return true (and print the 1st message) even when I'm sure there is no connection. What I'm doing wrong?

PS:我还在学习C#

P.S.: I'm still learning C#.

推荐答案

请纠正我,如果我错了,但据我可以看到你正在使用的方法是检查的网络的连接,而不一定的网络的连接。如果你是一个网络的任何形式的,这将返回true,无论互联网是可用还是不上我会承担?请参见这个

Please correct me if I am wrong but as far as I can see the method you are using is checking network connectivity and not necessarily internet connectivity. I would assume if you are on a network of any sort this would return true regardless of the internet being available or not? See this.

我注意到,检查互联网连接的一种方式如下:

I have noticed that one way of checking for internet connectivity is as follows:

private bool IsInternetAvailable()
{
    try
    {
        Dns.GetHostEntry("www.google.com"); //using System.Net;
        return true;
    } catch (SocketException ex) {
        return false;
    }
}



上面的代码可以发现(在VB.Net通过在以下的帖子

注:最新的编辑由 AceInfinity 的建议,但在群体审查被驳回。我的信誉太低,无法覆盖此所以我做了改变自己。

Note: The latest edit was suggested by AceInfinity but was rejected in community review. My reputation is too low to override this so I made the change myself.

这篇关于为什么GetIsNetworkAvailable()总是返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆