如何检查networking连接?
确定是否有可用的networking连接的最佳方法是什么?
您可以使用GetIsNetworkAvailable()
在.NET 2.0中检查networking连接:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
要监视IP地址的变化或networking可用性的变化,请使用NetworkChange类中的事件:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
标记的答案是100%,但是,有些情况下,标准方法被虚拟卡(虚拟盒,…)愚弄。 丢弃一些基于速度的networking接口(串口,调制解调器等)也是经常需要的。
这是一个检查这些情况的代码片段:
/// <summary> /// Indicates whether any network connection is available /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable() { return IsNetworkAvailable(0); } /// <summary> /// Indicates whether any network connection is available. /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable(long minimumSpeed) { if (!NetworkInterface.GetIsNetworkAvailable()) return false; foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { // discard because of standard reasons if ((ni.OperationalStatus != OperationalStatus.Up) || (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) || (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel)) continue; // this allow to filter modems, serial, etc. // I use 10000000 as a minimum speed for most cases if (ni.Speed < minimumSpeed) continue; // discard virtual cards (virtual box, virtual pc, etc.) if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) || (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0)) continue; // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card. if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase)) continue; return true; } return false; }
Microsoft Windows Vista和7使用NCSI(networking连接状态指示器)技术:
- NCSI在www.msftncsi.com上执行DNS查询,然后请求http://www.msftncsi.com/ncsi.txt 。 该文件是纯文本文件,仅包含文本“ Microsoft NCSI ”。
- NCSI向dns.msftncsi.com发送DNS查找请求。 这个DNS地址应该parsing为131.107.255.255。 如果地址不匹配,则认为互联网连接无法正常工作。
调用此方法检查networking连接。
public static bool IsConnectedToInternet() { bool returnValue = false; try { int Desc; returnValue = Utility.InternetGetConnectedState(out Desc, 0); } catch { returnValue = false; } return returnValue; }
把这下面的代码行。
[DllImport("wininet.dll")] public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);