119

What is the best way to determine if there is a network connection available?

1

4 Answers 4

190

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <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;
    }
11
  • 17
    this is correct and deserves many upvotes - I found that the NetworkAvailabilityChanged event mentioned in the accepted answer is not reliably fired, which is probably caused by virtual adapters as mentioned in this answer
    – Marek
    Commented Feb 9, 2012 at 13:15
  • 1
    +1 for the additional check for virtual machines. Just run into this case yesterday. But I still think this doesn't handle 'Hype-V', due to they don't have 'virtual' in their name. Commented Apr 23, 2014 at 6:35
  • 3
    @Herdo - yes, the code's not perfect, and I don't think there can be anything perfect in a virtual world. But you can improve it. Commented Apr 23, 2014 at 7:52
  • @SimonMourier You are right. Just wanted to note that, if anybody gets still returned true, if there is no connection --> This might be an issue :) Commented Apr 23, 2014 at 7:56
  • 1
    @noelicus - On projects I have been working on so far, I have implemented a periodic monitoring/polling system (simple HTTP GET requests because I was targeting a web server) which raises events when the server is detected as "down" (not reachable by HTTP) or "up" (reachable again). In the general case, you can define what "reliable" means in your case, and implement a similar logic. Commented Feb 13, 2015 at 18:26
159

You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
6
  • 9
    Does this take care of "limited availability"?
    – tofutim
    Commented Sep 13, 2011 at 0:51
  • This doesn't always work in WPF. Some laptops return false and some return true
    – krilovich
    Commented Feb 10, 2016 at 17:21
  • Is this really work? I just wrote this line and turn my router off and still returns true!
    – Mushfiq
    Commented May 20, 2017 at 23:37
  • 1
    NetworkInterface.GetIsNetworkAvailable() has been very unreliable in my application (.NET 4.5, Windows 10), especially when running in a virtual machine. Handling the events from NetworkAvailabilityChanged has been reliable.
    – eskimwier
    Commented Sep 14, 2017 at 15:16
  • That is not reliable. read stackoverflow.com/a/25779403/2377343
    – T.Todua
    Commented Sep 9, 2019 at 11:17
10

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.
1
  • 3
    This is great, but is not technically about the availability of a 'network' but more 'do I have internet connectivity via http?' You can have perfect network connections but no connectivity to the internet, for instance on a stand-alone lan. See for more info om NCSI: technet.microsoft.com/en-us/library/cc766017.aspx
    – MichielB
    Commented Jan 16, 2015 at 13:16
0

Call this method to check the network Connection.

public static bool IsConnectedToInternet()
        {
            bool returnValue = false;
            try
            {

                int Desc;
                returnValue = Utility.InternetGetConnectedState(out Desc, 0);
            }
            catch
            {
                returnValue = false;
            }
            return returnValue;
        }

Put this below line of code.

[DllImport("wininet.dll")]
        public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.