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


当前回答

不能解决在检查和运行代码之间网络中断的问题吗 但是相当可靠

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

其他回答

public static bool Isconnected = false;

public static bool CheckForInternetConnection()
{
    try
    {
        Ping myPing = new Ping();
        String host = "google.com";
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions pingOptions = new PingOptions();
        PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
        if (reply.Status == IPStatus.Success)
        {
            return true;
        }
        else if (reply.Status == IPStatus.TimedOut)
        {
            return Isconnected;
        }
        else
        {
            return false;
        }
    }
    catch (Exception)
    {
        return false;
    }
}

public static void CheckConnection()
{
    if (CheckForInternetConnection())
    {
        Isconnected = true;
    }
    else
    {
        Isconnected = false;
    }
}

另一种选择是网络列表管理器API,它适用于Vista和Windows 7。MSDN文章在这里。在本文中有一个下载代码示例的链接,允许您这样做:

AppNetworkListUser nlmUser = new AppNetworkListUser();
Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());

请确保从COM选项卡中添加对网络列表1.0类型库的引用…它将显示为NETWORKLIST。

bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

if (bb == true)
    MessageBox.Show("Internet connections are available");
else
    MessageBox.Show("Internet connections are not available");

通过ping谷歌测试网络连接:

new Ping().Send("www.google.com.mx").Status == IPStatus.Success

我已经看到了上面列出的所有选项,唯一可行的选项来检查互联网是否可用是“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的情况下,没有办法知道互联网连接是否可用。