确定是否有可用的网络连接的最佳方法是什么?
标记的答案是100%罚款,但是,在某些情况下标准方法被虚拟卡(虚拟盒,...)欺骗.通常还需要根据速度(串行端口,调制解调器......)丢弃某些网络接口.
这是一段检查这些情况的代码:
////// Indicates whether any network connection is available /// Filter connections below a specified speed, as well as virtual network cards. /// ////// public static bool IsNetworkAvailable() { return IsNetworkAvailable(0); } ///true if a network connection is available; otherwise,false . ////// Indicates whether any network connection is available. /// Filter connections below a specified speed, as well as virtual network cards. /// /// The minimum speed required. Passing 0 will not filter connection using speed. ////// 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; }true if a network connection is available; otherwise,false . ///
您可以使用以下命令检查.NET 2.0中的网络连接GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
要监视IP地址的更改或网络可用性的更改,请使用NetworkChange类中的事件:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
Microsoft Windows Vista和7使用NCSI(网络连接状态指示器)技术:
NCSI在www.msftncsi.com上执行DNS查找,然后请求http://www.msftncsi.com/ncsi.txt.此文件是纯文本文件,仅包含文本" Microsoft NCSI ".
NCSI发送dns.msftncsi.com的DNS查找请求.此DNS地址应解析为131.107.255.255.如果地址不匹配,则假定互联网连接无法正常运行.