check internet continuously

ahmedAlie 161 Reputation points
2022-01-24T11:59:46.463+00:00

hi

I want a way to check the Internet continuously and quickly and does not affect the interface of the program when it is working, and it checks continuously and is sensitive to the Internet.

The code I made actually works and takes a lot of time to check and is not sensitive.

//check  class TIMEDATE_INTER
public static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                using (client.OpenRead("http://google.com/generate_204"))
                    return true;
            }
            catch
            {
                return false;
            }
        }


// check result in timer  tnterval =5

 if (TIMEDATE_INTER.CheckForInternetConnection() == true)
                {

                    label5.Invoke((MethodInvoker)delegate
                    {
                        label5.Text = "internet connect";
                        return;

                    });

                }
                else 
                {
                    label5.Invoke((MethodInvoker)delegate
                    {
                        label5.Text = "internet disconnect";

                        return;
                    });

                    //
                }
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-01-24T14:38:55.697+00:00

    Here is a asynchronous method

    Full source showing how to call.

    using System.Diagnostics;  
    using System.Net;  
    using System.Net.NetworkInformation;  
    using System.Net.Sockets;  
    using System.Threading.Tasks;  
      
    namespace HelpersUtilitiesProject  
    {  
        class Utilities  
        {  
            public static async Task<bool> IsConnectedToInternetAsync()  
            {  
                const int maxHops = 30;  
                const string someFarAwayIpAddress = "8.8.8.8";  
      
                for (int ttl = 1; ttl <= maxHops; ttl++)  
                {  
                    var options = new PingOptions(ttl, true);  
                    byte[] buffer = new byte[32];  
      
                    PingReply reply;  
      
                    try  
                    {  
                        using (var pinger = new Ping())  
                        {  
                            reply = await pinger.SendPingAsync(  
                                someFarAwayIpAddress,   
                                10000,   
                                buffer,   
                                options);  
                        }  
                    }  
                    catch (PingException pingex)  
                    {  
                        //Debug.Print($"Ping exception (probably due to no network connection or recent change in network conditions), hence not connected to internet. Message: {pingex.Message}");  
                        return false;  
                    }  
      
                    string address = reply.Address?.ToString() ?? null;  
                    //Debug.Print($"Hop #{ttl} is {address}, {reply.Status}");  
      
                    if (reply.Status != IPStatus.TtlExpired && reply.Status != IPStatus.Success)  
                    {  
                        //Debug.Print($"Hop #{ttl} is {reply.Status}, hence we are not connected.");  
                        return false;  
                    }  
      
                    if (IsRoutableAddress(reply.Address))  
                    {  
                        //Debug.Print("That's routable, so we must be connected to the internet.");  
                        return true;  
                    }  
                }  
      
                return false;  
            }  
      
            private static bool IsRoutableAddress(IPAddress addr)  
            {  
                if (addr == null)  
                {  
                    return false;  
                }  
                else if (addr.AddressFamily == AddressFamily.InterNetworkV6)  
                {  
                    return !addr.IsIPv6LinkLocal && !addr.IsIPv6SiteLocal;  
                }  
                else // IPv4  
                {  
                    byte[] bytes = addr.GetAddressBytes();  
                    if (bytes[0] == 10)  
                    {   // Class A network  
                        return false;  
                    }  
                    else if (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)  
                    {   // Class B network  
                        return false;  
                    }  
                    else if (bytes[0] == 192 && bytes[1] == 168)  
                    {   // Class C network  
                        return false;  
                    }  
                    else  
                    {   // None of the above, so must be routable  
                        return true;  
                    }  
                }  
            }  
        }  
      
    }  
      
    

    Form code

    private async void InternetCheckButton_Click(object sender, EventArgs e)  
    {  
        await Task.Run(async () =>  
        {  
            var result = await Utilities.IsConnectedToInternetAsync();  
            MessageBox.Show(result ? "Available" : "Not available");  
        });  
    }  
    

    Edit

    Refactored code to work with a Timer (link above points to the revised code)

    using System;  
    using System.Windows.Forms;  
    using HelpersUtilitiesProject.Classes;  
      
    namespace HelpersUtilitiesProject  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
      
                TimerHelper.Message += OnMessage;  
      
                Shown += OnShown;  
      
            }  
      
            private void OnShown(object sender, EventArgs e)  
            {  
                label1.Text = "";  
                TimerHelper.Start();  
            }  
      
            private void OnMessage(string message) =>   
                label1.InvokeIfRequired(x => x.Text = message);  
        }  
    }  
      
    

    167849-figure1.png

    1 person found this answer helpful.

3 additional answers

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2022-01-24T12:06:37.337+00:00

    I think doing a ping would be quicker

     public bool IsConnectedToInternet()  
     {  
               string host = "http://www.google.com";  
               bool result = false;  
               Ping p = new Ping();  
                try  
                {  
                      PingReply reply = p.Send(host, 3000);  
                      if (reply.Status == IPStatus.Success)  
                            return true;  
                 }  
                 catch { }  
                 return result;  
        }
    

    https://www.c-sharpcorner.com/uploadfile/nipuntomar/check-internet-connection/

    0 comments No comments

  2. Castorix31 90,681 Reputation points
    2022-01-24T12:38:19.117+00:00

    You can use in a Thread one of the various methods to check Internet connectivity
    IsInternetConnected, InternetGetConnectedState, NetworkInformation (Windows.Networking.Connectivity), INetworkListManager, INetworkConnectionEvents, etc...

    0 comments No comments

  3. KOZ6.0 6,655 Reputation points
    2024-04-02T21:28:13.77+00:00

    Depending on your network configuration, pings may not be forwarded to the outside world (allowing connections only through a proxy). Also, there is no guarantee that the server will return a ping.

    The way Windows does it:

    https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/ee126135(v=ws.10)

    「Specific network interface IPv4 availability - No connectivity, Local, Internet」

    https://stackoverflow.com/questions/8027791/specific-network-interface-ipv4-availability-no-connectivity-local-internet

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.