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

标签 c# networking

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

最佳答案

标记的答案是 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/

相关文章:

c# - ASP.NET MVC 自定义多字段验证

c# - Func<> 委托(delegate) - 说明

c# - 如何在不尊重某些字符的情况下对列表进行排序?

c# - 如何将 Ninject 命名绑定(bind)与 DependencyResolver 和 PropertyInjection 一起使用

c# - 非回溯子表达式如何工作 "(?>exp)"

windows - Linux 到 WinXP over UDP 滞后

java - 如何在 Java 中通过多个线程发送消息?

iphone - (iphone) 特定 IP/端口的可达性测试?

c - 从客户端接受数据时出现段错误

c# - Internet 上的客户端-服务器应用程序消息交换