gpt4 book ai didi

c# - 如何检查网络连接?

转载 作者:IT王子 更新时间:2023-10-29 03:34:51 31 4
gpt4 key购买 nike

确定是否存在可用网络连接的最佳方法是什么?

最佳答案

标记的答案是 100% 没问题,但是,在某些情况下,标准方法会被虚拟卡片(虚拟盒子,...)所欺骗。通常还需要根据速度丢弃某些网络接口(interface)(串行端口、调制解调器……)。

这是检查这些情况的一段代码:

    /// <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;
}

关于c# - 如何检查网络连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/520347/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com