什么是确认有可用的网络连接,最简单的方法?最简单、方法、网络

2023-09-03 09:43:41 作者:君佛

我有点新手到C#/。NET的发展,但我已经把股票跟踪应用程序在我公司的一小部分资产。我还建立了它所连接的数据库在SQL 2000

I'm a bit of newbie to c#/.net development, but I've put together a stock tracking application for a small set of assets in my company. I have also set up the database it connects to in SQL 2000.

目前,它出色的作品,当网络连接是可用的,但我想展开它的使用,当我离开的连接。

It currently works brilliantly when a network connection is available, but I want to expand it for use when I'm away from a connection.

首先我需要知道是否有可用的连接。所以我把这个在一起:

First off I'll need to know if there's a connection available. So I put this together:

    private int availableNetAdapters()
    {
        int nicCount = 0;
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                nicCount++;
            }
        }

        return nicCount;
    }

似乎工作,但我要测试> 1的东西为MS TCP环回接口总是检测不管对方适配器张祖兴的。

Seems to work, but I have to test for ">1" as something as "MS TCP Loopback interface" is always detected regardless of the other adapter sates.

有没有更好/更简单的方法来检查连接?

Is there a better/easier way to check connectivity?

推荐答案

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

您也可以使用事件 NetworkAvailabilityChanged NetworkAddressChanged 在该类监测的IP地址和网络可用性的变化。

You can also use the events NetworkAvailabilityChanged and NetworkAddressChanged in that class to monitor IP address and network availability changes.

编辑:请注意,这种方法检查可能是电脑(无线,LAN等)上的所有可用的网络接口。如果他们中的任何一个连接,它将返回true。

Be aware that this method checks all available network interfaces that may be on the computer (wireless, lan, etc.). If anyone of them is connected, it will return true.