Check internet connection (availability) in C#

Check internet connection (availability) in C#

You can check for internet connectivity in C# by sending a ping request to a reliable server, such as Google's DNS server, and checking if a response is received. Here's an example code snippet:

using System.Net.NetworkInformation;

public static bool CheckInternetConnection()
{
    try
    {
        Ping myPing = new Ping();
        string host = "8.8.8.8"; // Google's DNS server
        byte[] buffer = new byte[32];
        int timeout = 1000; // Timeout in milliseconds
        PingOptions options = new PingOptions();
        PingReply reply = myPing.Send(host, timeout, buffer, options);
        return (reply.Status == IPStatus.Success);
    }
    catch (Exception)
    {
        return false;
    }
}

This method returns a boolean value indicating whether an internet connection is available or not.

Examples

  1. "C# check if the internet connection is available using Ping"

    using System.Net.NetworkInformation;
    
    public bool IsInternetAvailable()
    {
        try
        {
            using (var ping = new Ping())
            {
                var reply = ping.Send("www.google.com", 3000);
                return reply != null && reply.Status == IPStatus.Success;
            }
        }
        catch (PingException)
        {
            return false;
        }
    }
    

    Code Description: Use the Ping class to send a ping request to a known host (e.g., Google) and check for a successful response.

  2. "C# check internet connection using NetworkInterface"

    using System.Net.NetworkInformation;
    
    public bool IsInternetAvailable()
    {
        return NetworkInterface.GetIsNetworkAvailable();
    }
    

    Code Description: Use the NetworkInterface class to check if any network interface is available, indicating a potential internet connection.

  3. "C# check internet connection using HttpClient"

    using System.Net.Http;
    
    public async Task<bool> IsInternetAvailableAsync()
    {
        try
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync("http://www.google.com");
                return response.IsSuccessStatusCode;
            }
        }
        catch (HttpRequestException)
        {
            return false;
        }
    }
    

    Code Description: Use the HttpClient to send a simple HTTP request to a known endpoint (e.g., Google) and check for a successful response.

  4. "C# check internet connection using Dns.GetHostAddresses"

    using System.Net;
    
    public bool IsInternetAvailable()
    {
        try
        {
            var addresses = Dns.GetHostAddresses("www.google.com");
            return addresses.Length > 0;
        }
        catch (Exception)
        {
            return false;
        }
    }
    

    Code Description: Use Dns.GetHostAddresses to resolve the IP addresses associated with a host and check if any addresses are returned.

  5. "C# check internet connection using WebRequest"

    using System.Net;
    
    public bool IsInternetAvailable()
    {
        try
        {
            var request = WebRequest.Create("http://www.google.com");
            using (var response = request.GetResponse())
            {
                return true;
            }
        }
        catch (WebException)
        {
            return false;
        }
    }
    

    Code Description: Use WebRequest to create a request to a known endpoint and check for a successful response.

  6. "C# check internet connection using InternetGetConnectedState"

    using System.Runtime.InteropServices;
    
    public static class InternetConnectionHelper
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int description, int reservedValue);
    
        public static bool IsInternetAvailable()
        {
            return InternetGetConnectedState(out _, 0);
        }
    }
    

    Code Description: Use the InternetGetConnectedState function from wininet.dll to check the overall internet connection state.

  7. "C# check internet connection using Socket"

    using System.Net.Sockets;
    
    public bool IsInternetAvailable()
    {
        try
        {
            using (var client = new TcpClient("www.google.com", 80))
            {
                return true;
            }
        }
        catch (SocketException)
        {
            return false;
        }
    }
    

    Code Description: Use a TcpClient to attempt a connection to a known host (e.g., Google) and check for successful socket connection.

  8. "C# check internet connection using System.Net.NetworkInformation Reachability"

    using System.Net.NetworkInformation;
    
    public bool IsInternetAvailable()
    {
        try
        {
            var internetSettings = IPGlobalProperties.GetIPGlobalProperties();
            var endpoints = internetSettings.GetActiveTcpListeners();
            return endpoints.Length > 0;
        }
        catch (NetworkInformationException)
        {
            return false;
        }
    }
    

    Code Description: Use IPGlobalProperties to retrieve information about the network interfaces and check if there are active TCP listeners.

  9. "C# check internet connection using System.Net.NetworkInformation Interface Properties"

    using System.Net.NetworkInformation;
    
    public bool IsInternetAvailable()
    {
        try
        {
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            return networkInterfaces.Any(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback);
        }
        catch (NetworkInformationException)
        {
            return false;
        }
    }
    

    Code Description: Use NetworkInterface to retrieve information about network interfaces and check if any operational interfaces are not of type Loopback.

  10. "C# check internet connection using WebClient"

    using System.Net;
    
    public bool IsInternetAvailable()
    {
        try
        {
            using (var client = new WebClient())
            using (client.OpenRead("http://www.google.com"))
            {
                return true;
            }
        }
        catch (WebException)
        {
            return false;
        }
    }
    

    Code Description: Use WebClient to open a read stream from a known URL (e.g., Google) and check for successful connection.


More Tags

serverless android-architecture-components structure inject java.util.date mongodb-oplog properties-file .net-framework-version domain-name simplexml

More C# Questions

More Bio laboratory Calculators

More Chemistry Calculators

More Electronics Circuits Calculators

More Mortgage and Real Estate Calculators