【问题标题】:How to determine if network interface is connected to the Internet (i. e. the computer is online)如何判断网络接口是否连接到互联网(即电脑是否在线)
【发布时间】:2011-04-24 18:10:17
【问题描述】:

我需要一种以编程方式确定互联网可用性的方法。 现在我使用 Ping 不断地 ping 一些互联网站点。

但似乎 Windows 7 以其他方式决定了互联网的可用性。 如果计算机在线,系统托盘中的网络接口图标上有地球图标。

问题是:是否有任何标准的 Win32 方法来检查在线状态、获胜事件或其他内容,如果有,如何在 C# 中使用它?

【问题讨论】:

  • 您打算如何处理这些信息?由于互联网连接可能随时中断,因此无论如何您都必须进行防御性编程。
  • 嗯,我有一个重新启用 LAN 接口的代码。
  • 它通过 WMI 禁用 LAN 接口,然后再次启用 - 当提供商方面出现一些问题时,它会有所帮助。我还计划设置一个 WiMax 或 GS​​M 调制解调器,因为连接我的应用程序非常关键:)

标签: c# networking windows-7 windows-services


【解决方案1】:

我相信这样的事情会起作用,尽管您的问题似乎是重复的:

using System;
using System.Runtime;
using System.Runtime.InteropServices;

public class InternetCS
{
    //Creating the extern function...
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );

    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet( )
    {
        int Desc ;
        return InternetGetConnectedState( out Desc, 0 ) ;
    }
}

在这里找到:

check whether Internet connection is available with C#

【讨论】:

    【解决方案2】:

    “连接到互联网”没有任何实际意义,除非是调制解调器。测试任何资源是否可用的最佳方法是使用它。无论如何,您必须在那个时候应对失败,无需将所有内容编码两次。

    【讨论】:

    • 嗯,它已经这样做了。每 3 秒我向一个众所周知的公共主机发送 ping,如果我失败至少 10 个周期 - 我重新启动网络接口。
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2010-11-19
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多