What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2044
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

相关标签:
27条回答
  • 2020-11-22 08:18

    If you want to notify the user/take action whenever a network/connection change occur.
    Use NLM API:

    • https://msdn.microsoft.com/en-us/library/ee264321.aspx

    • http://www.codeproject.com/Articles/34650/How-to-use-the-Windows-NLM-API-to-get-notified-of

    0 讨论(0)
  • 2020-11-22 08:18

    I personally find the answer of Anton and moffeltje best, but I added a check to exclude virtual networks set up by VMWare and others.

    public static bool IsAvailableNetworkActive()
    {
        // only recognizes changes related to Internet adapters
        if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) return false;
    
        // however, this will include all adapters -- filter by opstatus and activity
        NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
        return (from face in interfaces
                where face.OperationalStatus == OperationalStatus.Up
                where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                where (!(face.Name.ToLower().Contains("virtual") || face.Description.ToLower().Contains("virtual")))
                select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
    }
    
    0 讨论(0)
  • 2020-11-22 08:18

    Multi threaded version of ping:

      using System;
      using System.Collections.Generic;
      using System.Diagnostics;
      using System.Net.NetworkInformation;
      using System.Threading;
    
    
      namespace OnlineCheck
      {
          class Program
          {
    
              static bool isOnline = false;
    
              static void Main(string[] args)
              {
                  List<string> ipList = new List<string> {
                      "1.1.1.1", // Bad ip
                      "2.2.2.2",
                      "4.2.2.2",
                      "8.8.8.8",
                      "9.9.9.9",
                      "208.67.222.222",
                      "139.130.4.5"
                      };
    
                  int timeOut = 1000 * 5; // Seconds
    
    
                  List<Thread> threadList = new List<Thread>();
    
                  foreach (string ip in ipList)
                  {
    
                      Thread threadTest = new Thread(() => IsOnline(ip));
                      threadList.Add(threadTest);
                      threadTest.Start();
                  }
    
                  Stopwatch stopwatch = Stopwatch.StartNew();
    
                  while (!isOnline && stopwatch.ElapsedMilliseconds <= timeOut)
                  {
                       Thread.Sleep(10); // Cooldown the CPU
                  }
    
                  foreach (Thread thread in threadList)
                  { 
                      thread.Abort(); // We love threads, don't we?
                  }
    
    
                  Console.WriteLine("Am I online: " + isOnline.ToYesNo());
                  Console.ReadKey();
              }
    
              static bool Ping(string host, int timeout = 3000, int buffer = 32)
              {
                  bool result = false;
    
                  try
                  {
                      Ping ping = new Ping();                
                      byte[] byteBuffer = new byte[buffer];                
                      PingOptions options = new PingOptions();
                      PingReply reply = ping.Send(host, timeout, byteBuffer, options);
                      result = (reply.Status == IPStatus.Success);
                  }
                  catch (Exception ex)
                  {
    
                  }
    
                  return result;
              }
    
              static void IsOnline(string host)
              {
                  isOnline =  Ping(host) || isOnline;
              }
          }
    
          public static class BooleanExtensions
          {
              public static string ToYesNo(this bool value)
              {
                  return value ? "Yes" : "No";
              }
          }
      }
    
    0 讨论(0)
  • 2020-11-22 08:18

    I wouldn't think it's impossible, just not straightforward.

    I've built something like this, and yes it's not perfect, but the first step is essential: to check if there's any network connectivity. The Windows Api doesn't do a great job, so why not do a better job?

    bool NetworkIsAvailable()
    {
        var all = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
        foreach (var item in all)
        {
            if (item.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                continue;
            if (item.Name.ToLower().Contains("virtual") || item.Description.ToLower().Contains("virtual"))
                continue; //Exclude virtual networks set up by VMWare and others
            if (item.OperationalStatus == OperationalStatus.Up)
            {
                return true;
            }
        }
    
        return false;
    }
    

    It's pretty simple, but it really helps improve the quality of the check, especially when you want to check various proxy configurations.

    So:

    • Check whether there's network connectivity (make this really good, maybe even have logs sent back to developers when there are false positives to improve the NetworkIsAvailable function)
    • HTTP Ping
    • (Cycle through Proxy configurations with HTTP Pings on each)
    0 讨论(0)
  • 2020-11-22 08:19

    Use NetworkMonitor to monitoring network state and internet connection.

    Sample:

    namespace AmRoNetworkMonitor.Demo
    {
        using System;
    
        internal class Program
        {
            private static void Main()
            {
                NetworkMonitor.StateChanged += NetworkMonitor_StateChanged;
                NetworkMonitor.StartMonitor();
    
                Console.WriteLine("Press any key to stop monitoring.");
                Console.ReadKey();
                NetworkMonitor.StopMonitor();
    
                Console.WriteLine("Press any key to close program.");
                Console.ReadKey();
            }
    
            private static void NetworkMonitor_StateChanged(object sender, StateChangeEventArgs e)
            {
                Console.WriteLine(e.IsAvailable ? "Is Available" : "Is Not Available");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:20

    Introduction

    In some scenarios you need to check whether internet is available or not using C# code in windows applications. May be to download or upload a file using internet in windows forms or to get some data from database which is at remote location, in these situations internet check is compulsory.

    There are some ways to check internet availability using C# from code behind. All such ways are explained here including their limitations.

    1. InternetGetConnectedState(wininet)

    The 'wininet' API can be used to check the local system has active internet connection or not. The namespace used for this is 'System.Runtime.InteropServices' and import the dll 'wininet.dll' using DllImport. After this create a boolean variable with extern static with a function name InternetGetConnectedState with two parameters description and reservedValue as shown in example.

    Note: The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code. In this case, the method must also be declared as static.

    Next create a method with name 'IsInternetAvailable' as boolean. The above function will be used in this method which returns internet status of local system

    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int description, int reservedValue);
    public static bool IsInternetAvailable()
    {
        try
        {
            int description;
            return InternetGetConnectedState(out description, 0);
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    
    1. GetIsNetworkAvailable

    The following example uses the GetIsNetworkAvailable method to determine if a network connection is available.

    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
    {
        System.Windows.MessageBox.Show("This computer is connected to the internet");
    }
    else
    {
        System.Windows.MessageBox.Show("This computer is not connected to the internet");
    }
    

    Remarks (As per MSDN): A network connection is considered to be available if any network interface is marked "up" and is not a loopback or tunnel interface.

    There are many cases in which a device or computer is not connected to a useful network but is still considered available and GetIsNetworkAvailable will return true. For example, if the device running the application is connected to a wireless network that requires a proxy, but the proxy is not set, GetIsNetworkAvailable will return true. Another example of when GetIsNetworkAvailable will return true is if the application is running on a computer that is connected to a hub or router where the hub or router has lost the upstream connection.

    1. Ping a hostname on the network

    Ping and PingReply classes allows an application to determine whether a remote computer is accessible over the network by getting reply from the host. These classes are available in System.Net.NetworkInformation namespace. The following example shows how to ping a host.

    protected bool CheckConnectivity(string ipAddress)
    {
        bool connectionExists = false;
        try
        {
            System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
            options.DontFragment = true;
            if (!string.IsNullOrEmpty(ipAddress))
            {
                System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddress);
                connectionExists = reply.Status == 
    System.Net.NetworkInformation.IPStatus.Success ? true : false;
            }
        }
        catch (PingException ex)
        {
            Logger.LogException(ex.Message, ex);
        }
        return connectionExists;
    }
    

    Remarks (As per MSDN): Applications use the Ping class to detect whether a remote computer is reachable. Network topology can determine whether Ping can successfully contact a remote host. The presence and configuration of proxies, network address translation (NAT) equipment, or firewalls can prevent Ping from succeeding. A successful Ping indicates only that the remote host can be reached on the network; the presence of higher level services (such as a Web server) on the remote host is not guaranteed.

    Comments/Suggestions are invited. Happy coding......!

    0 讨论(0)
提交回复
热议问题