C#检查Internet连接

 吴雨醒 发布于 2023-02-13 16:29

你有没有办法告诉我是否有办法在我的C#程序运行时检查我的电脑中是否有互联网连接.举一个简单的例子,如果互联网工作,我会输出一个消息框说Internet is available.否则我会输出一条消息说,Internet is unavailable.

不使用库函数来查看网络是否可用(因为这不检查互联网连接)

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

或者不打开网页并查看它是否返回数据

using (WebClient client = new WebClient())
      htmlCode = client.DownloadString("http://google.com");

因为上述两种方法都不适合我的需要.

2 个回答
  • 更短的版本:

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

    另一种选择是:

    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) {
      // presumably online
    }
    

    你可以在这里找到更广泛的讨论

    2023-02-13 16:32 回答
  • 请考虑以下代码段...

    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) 
    {
      // presumably online
    }
    

    祝好运!

    2023-02-13 16:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有