Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to verify there's an available network connection?

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

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?

G

like image 982
G-. Avatar asked Feb 03 '09 16:02

G-.


People also ask

How do you verify the status of a network connection?

Windows 11 lets you quickly check your network connection status. Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.

What can be used to check network connectivity?

Answer: To test connectivity with a host on a network or internetwork, use the PING utility.


1 Answers

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

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

EDIT: 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.

like image 71
Luke Avatar answered Oct 17 '22 09:10

Luke