首页 / .NET / 正文

[.NET/C#].NET/C#应用程序开发中检测网络连接是否可用的方法有哪些,哪种方式最好呢?

2219 1 发布于: 2018-11-02 读完约需6分钟

问题描述

如题,在.NET/C#应用程序开发中检测网络连接是否可用的方法有哪些,哪种方式又是最好呢?

方案一

使用System.Net.WebClient类的OpenRead方法,如下:

public static bool CheckForInternetConnection()
{
    try
    {
        using (var client = new WebClient())
        using (client.OpenRead("http://clients3.google.com/generate_204"))
        {
            return true;
        }
    }
    catch
    {
        return false;
    }
}

方案二

使用Ping类,如下:

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);
    return (reply.Status == IPStatus.Success);
}
catch (Exception) {
    return false;
}

方案三

使用Windows的动态链接库wininet.dll中的InternetGetConnectedState方法,如下:

[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

public static bool CheckNet()
{
     int desc;
     return InternetGetConnectedState(out desc, 0);         
}

方案四

使用System.Net.NetworkInformation.NetworkInterface的静态方法GetIsNetworkAvailable(),如下:

public static bool IsAvailableNetworkActive()
{
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
    {
        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;
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [.NET/C#].NET/C#应用程序开发中如何将一个URL参数字符串转换成NameValueCollection对象?

下一篇: [ASP.NET Core]ASP.NET Core应用程序开发中如何手动解决获取依赖注入(DI)的实例?

本文永久链接码友网 » [.NET/C#].NET/C#应用程序开发中检测网络连接是否可用的方法有哪些,哪种方式最好呢?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册