不断检查互联网连接

如何在我的应用程序中不断检查互联网连接,如果连接不可用则进行响应?

目前我正在使用:

while(true) { if(HasConnection()) { //doSomething.. } //stop app by 1sec } 

但它似乎相当不优雅。

超级用户对此问题的接受答案描述了Windows确定其是否具有网络访问权限的方式。 您可以使用类似的方法,但是当您的应用程序启动时,我会生成一个单独的线程负责进行检查。 让单独的线程以您认为最好的方式执行检查,并在连接状态更改时引发事件。

您正在寻找NetworkAvailabilityChanged事件 。

要检查互联网连接,您可以ping一个可靠的网站,例如Google.com。

请注意,无法通知互联网连接的每次更改(例如ISP中断)。

使用以下代码:

 public static class LocalSystemConnection { [DllImport("wininet.dll", SetLastError=true, CallingConvention = CallingConvention.ThisCall)] extern static bool InternetGetConnectedState(out ConnectionStates lpdwFlags, long dwReserved); ///  /// Retrieves the connected state of the local system. ///  /// A  value that receives the connection description. ///  /// A return value of true indicates that either the modem connection is active, or a LAN connection is active and a proxy is properly configured for the LAN. /// A return value of false indicates that neither the modem nor the LAN is connected. /// If false is returned, the  flag may be set to indicate that autodial is configured to "always dial" but is not currently active. /// If autodial is not configured, the function returns false. ///  public static bool IsConnectedToInternet(out ConnectionStates connectionStates) { connectionStates = ConnectionStates.Unknown; return InternetGetConnectedState(out connectionStates, 0); } ///  /// Retrieves the connected state of the local system. ///  ///  /// A return value of true indicates that either the modem connection is active, or a LAN connection is active and a proxy is properly configured for the LAN. /// A return value of false indicates that neither the modem nor the LAN is connected. /// If false is returned, the  flag may be set to indicate that autodial is configured to "always dial" but is not currently active. /// If autodial is not configured, the function returns false. ///  public static bool IsConnectedToInternet() { ConnectionStates state = ConnectionStates.Unknown; return IsConnectedToInternet(out state); } } [Flags] public enum ConnectionStates { ///  /// Unknown state. ///  Unknown = 0, ///  /// Local system uses a modem to connect to the Internet. ///  Modem = 0x1, ///  /// Local system uses a local area network to connect to the Internet. ///  LAN = 0x2, ///  /// Local system uses a proxy server to connect to the Internet. ///  Proxy = 0x4, ///  /// Local system has RAS (Remote Access Services) installed. ///  RasInstalled = 0x10, ///  /// Local system is in offline mode. ///  Offline = 0x20, ///  /// Local system has a valid connection to the Internet, but it might or might not be currently connected. ///  Configured = 0x40, } 

如果您只需要知道是否有至少一个连接可用,您可以尝试这样做:

InternetGetConnectedStateEx()

http://msdn.microsoft.com/en-us/library/aa384705%28v=vs.85%29.aspx

你怎么知道你是否有互联网连接? 您是否可以将数据包路由到附近的路由器? 也许机器只有一个网卡,一个网关,也许网关的连接断电但机器仍然可以路由到网关和本地网络?

也许这台机器有一个网卡和十几个网关; 也许他们总是来去匆匆,但其中一个总是在起来?

如果机器有多个NIC但只有一个网关怎么办? 也许它可以路由到互联网的某个子集,但仍然可以很好地连接到未连接到互联网的本地网络?

如果机器有多个网卡,多个网关,但出于管理政策的原因,仍然只有部分互联网是可路由的,该怎么办?

您是否真的只关心客户是否与您的服务器连接?

数据包之间可以接受什么样的延迟? (30ms是好的,300ms正在推动人类耐力的极限,3000ms是无法忍受的长时间,960000ms是连接太阳探测器所需要的。)什么样的丢包是可以接受的?

真的想测量什么?

这将是一个开始,但正如sarnold所提到的,你需要考虑很多事情

您可以通过ping某些网站测试互联网连接,例如:

  public bool IsConnectedToInternet { try { using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping()) { string address = @"http://www.google.com";// System.Net.NetworkInformation.PingReply pingReplay = ping.Send(address);//you can specify timeout. if (pingReplay.Status == System.Net.NetworkInformation.IPStatus.Success) { return true; } } } catch { #if DEBUG System.Diagnostics.Debugger.Break(); #endif//DEBUG } return false; } 

如果你想连续检查然后使用计时器

  private Timer timer1; public void InitTimer() { timer1 = new Timer(); timer1.Tick += new EventHandler(timerEvent); timer1.Interval = 2000; // in miliseconds timer1.Start(); } private void timerEvent(object sender, EventArgs e) { DoSomeThingWithInternet(); } private void DoSomeThingWithInternet() { if (isConnected()) { // inform user that "you're connected to internet" } else { // inform user that "you're not connected to internet" } } public static bool isConnected() { try { using (var client = new WebClient()) using (client.OpenRead("http://clients3.google.com/generate_204")) { return true; } } catch { return false; } }