HOW TO CHECK INTERNET CONNECTION IS AVAILABLE IN C#?

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
C# 
C#
 2051  View(s)
Ratings:
Rate this:
Hi Mindstickians,

I'm developing one windows application, where we perform some task related to internet connection. 
So please tell me how to check internet connection is available or not in C#.

Thanks in advance. 
  1. Vijay Shukla

    Post:100

    Points:700
    Re: how to check internet connection is available in C#?

    Hello lois waisbrooker !
    Copy this code snippets and paste where which you want, This method return a bool type value and its parameter get a long value for minimumSpeed of your internet.

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!