确定是否有可用的网络连接的最佳方法是什么?
发布于 2009-02-06 13:53:25
您可以使用GetIsNetworkAvailable()
在.NET 2.0中检查网络连接
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
要监视IP地址的更改或网络可用性的更改,请使用NetworkChange类中的事件:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
发布于 2011-12-02 00:54:06
被标记的答案是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;
}
发布于 2016-07-04 16:09:04
调用此方法检查网络连接。
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);
https://stackoverflow.com/questions/520347
复制相似问题