How to check internet connectivity in C#

By FoxLearn 12/27/2024 2:09:50 AM   140
The method NetworkInterface.GetIsNetworkAvailable() in .NET, available since version 2.0, checks if a network connection is available.

However, it does not confirm if the connection is to the internet, as the network could be limited to a local network only. To verify internet connectivity, you can send an HTTP GET request to popular websites like microsoft.com or google.com.

The example described uses the Network Connectivity Status Indicator (NCSI) method, which is available in Windows OS (Vista and later). NCSI first attempts to reach the Microsoft NCSI test URL, and then checks the NCSI DNS IP address to ensure correct DNS configuration and validate internet connectivity.

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public class InternetConnectionChecker
{
    private const string NCSI_TEST_URL = "http://www.msftncsi.com/ncsi.txt";
    private const string NCSI_TEST_RESULT = "Microsoft NCSI";
    private const string NCSI_DNS = "dns.msftncsi.com";
    private const string NCSI_DNS_IP_ADDRESS = "131.107.255.255";

    public static async Task<bool> IsInternetConnectedAsync()
    {
        try
        {
            // Check NCSI test URL using HttpClient for async operations
            using (var client = new HttpClient())
            {
                string result = await client.GetStringAsync(NCSI_TEST_URL);
                if (result != NCSI_TEST_RESULT)
                {
                    return false;
                }
            }

            // Check NCSI DNS IP address
            var dnsHost = await Dns.GetHostAddressesAsync(NCSI_DNS);
            if (dnsHost.Length == 0 || dnsHost[0].ToString() != NCSI_DNS_IP_ADDRESS)
            {
                return false;
            }
        }
        catch (HttpRequestException ex)
        {
            // Handle specific web-related exceptions (HTTP request errors)
            Debug.WriteLine(ex);
            return false;
        }
        catch (SocketException ex)
        {
            // Handle DNS-related errors
            Debug.WriteLine(ex);
            return false;
        }
        catch (Exception ex)
        {
            // Catch any other unexpected errors
            Debug.WriteLine(ex);
            return false;
        }

        return true;
    }
}

The IsInternetConnectedAsync method uses asynchronous operations with HttpClient for non-blocking I/O.

We specifically catch HttpRequestException for web requests and SocketException for DNS issues, which gives more targeted error handling.