【发布时间】:2010-10-05 22:36:18
【问题描述】:
确定是否有可用网络连接的最佳方法是什么?
【问题讨论】:
标签: c# networking
确定是否有可用网络连接的最佳方法是什么?
【问题讨论】:
标签: c# networking
标记的答案是 100% 没问题,但是,在某些情况下,标准方法会被虚拟卡片(虚拟盒子,...)所欺骗。根据速度(串行端口、调制解调器等)丢弃一些网络接口通常也是可取的。
这是检查这些情况的一段代码:
/// <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;
}
【讨论】:
您可以使用GetIsNetworkAvailable() 在 .NET 2.0 中检查网络连接:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
要监控 IP 地址的变化或网络可用性的变化,请使用 NetworkChange 类中的事件:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
【讨论】:
NetworkInterface.GetIsNetworkAvailable() 在我的应用程序(.NET 4.5、Windows 10)中非常不可靠,尤其是在虚拟机中运行时。处理来自NetworkAvailabilityChanged 的事件是可靠的。
Microsoft windows vista 和 7 使用 NCSI(网络连接状态指示器)技术:
【讨论】:
调用此方法检查网络连接。
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);
【讨论】: