Hello. I am developing simple exercise formapp and I need to detect internet connection every 2 seconds.

#1. I do check internet connection like this

public static bool Connection()
        {
            bool connection;
            try
            {
                System.Net.IPHostEntry objIPHE = System.Net.Dns.GetHostEntry("www.google.com");
                connection = true;
            }
            catch
            {
                connection = false;
            }
            return connection;
        }

On mainForm I have 2 labels. First Getting green when bool connection is true (when false red), and Second getting text "Online" or "Offline".

try
            {
                if (Internet.Connection() == true)
                {
                    lblConnectivity.BackColor = System.Drawing.Color.Green;
                    lblConnectivityText.Text = "Online";
                }
                
            }
            catch
            {
                lblConnectivity.BackColor = System.Drawing.Color.Red;
                lblConnectivityText.Text = "Offline";
            }

Is there any more intelligent and professional approach to detect connection to internet instead of pinging Google?

Well, despite this method works, it doesn't react if I will switch connection off. I have an idea to use threading and it's method sleep(200).

// Internet is the name of class where static method Connection lives
// Gives error because Error	1	'bool MailClient.Internet.Connection()' has the //wrong return type

Tread connectionThread=new Thread(new ThreadStart(Internet.Connection));
connectionThread.Start();
connectionThread.Sleep(200);

Looks like ThreadStart can accept only void. Is there any other approach to work with threads when I need even return type method?

Thanks for any useful responses.

Hi there. In response to your threading question. You need to create a new ParameterizedThreadStart(method_name_goes_here) So when you call Thread.Start you can pass an array of Object. You cannot return a variable from a thread. (Where is it returning to?)

As for your other problem, there's no real way around that. Usually you would check against your own server. Also, getting the dns entry may give you an incorrect result if the name has been cached.

You may want to use "WebRequest" and then get the headers from the page. Be warned though, checking too often may lead to the IP of the user being banned from accessing that server! (Denial of Service)

If you want to simply check if you have an active network connection, the Windows API has some built in functions which check the status of the adapter. For direct-to-internet connections, this will obviously give you the online/offline status. But to anyone who connects through a router, this will only validate whether they are connected to the router or not.

Edited 6 Years Ago by Ketsuekiame: n/a

Thank you for reply. I had already tried

new ParameterizedThreadStart(Internet.Connection)

. The result is the same. I just need my method to return bool. So, I need to check bool value every n seconds. I need some approach like in skype.

If you want to simply check if you have an active network connection, the Windows API has some built in functions which check the status of the adapter.

Which functions?

Thank you for reply. I had already tried

new ParameterizedThreadStart(Internet.Connection)

. The result is the same. I just need my method to return bool. So, I need to check bool value every n seconds. I need some approach like in skype.

Which functions?

Yep, I noted afterwards that you cannot return a value from a thread. At the very least, you would need to use a shared variable and implement Thread safety/synchronisation around it. (You could get away with a simple Semaphore)

I don't use Skype so I don't really know what you're talking about with that one. But the generally method an application uses to determine if it's on-line is to communicate with its own server.

Eg. If I wrote an application that was an Instant Messenger, I would have a client for each user and a server that they would connect to. If I wished to determine if a user were still on-line, I would ping the central server. No reply means the server is down or the user is off-line.

The API function you need is InternetGetConnectedState and you will need to use P/Invoke to use it. Remember, even though it's named InternetGetConnectedState it will only return whether or not you are connected to a network on the LAN, unless you are plugged directly into a PPPoE or Modem connection.

Create a custom events with custom eventargs. After each attempt to connect raise an event with a bool, representating failed/success. And the method bound to this event will do the appropriate action depending on the bool.

Good evening! Thank you for your replies.

Eg. If I wrote an application that was an Instant Messenger, I would have a client for each user and a server that they would connect to. If I wished to determine if a user were still on-line, I would ping the central server. No reply means the server is down or the user is off-line.

My app is just a simple mail client (just a form to send mail...not much client). Thus, I just need to check even internet connectivity.

The API function you need is InternetGetConnectedState and you will need to use P/Invoke to use it. Remember, even though it's named InternetGetConnectedState it will only return whether or not you are connected to a network on the LAN, unless you are plugged directly into a PPPoE or Modem connection.

Thanks for this information. I'll study more to know to use it.

Create a custom events with custom eventargs. After each attempt to connect raise an event with a bool, representating failed/success. And the method bound to this event will do the appropriate action depending on the bool.

Can you provide me some example, please.

Hello, I am still alive! Looks like I've fond the best solution:

private void AddressChangedCallback(object sender, EventArgs e)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface n in adapters)
            {
                lblConnectivity.BackColor = System.Drawing.Color.Green;
                lblConnectivityText.Text = "Online";
            }
            }

and...

private void MainForm_Load(object sender, EventArgs e)
        {
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
        }

Well this does reacts good as I connect or disconnect internet. I use ZTE USB Modem.
Well now I have a problem how to set my indicators to proper state: -> Online, Offline? The thoughts I had were not working, such as to use if(n==true)...else...
Does someone can help me.

That will work fine for you, but for me (for example) that wouldn't. I have two network adapters and one is always connected via LAN. So your application would always indicate that I am on-line. Even if I unplugged the cable, because all you're doing is enumerating the number of devices in the system.

I assume you have no network ports, which makes the USB Modem your only network adapter.

I assume you have no network ports, which makes the USB Modem your only network adapter.

Right. I have only one modem and no any lan connections. But at moment I want to finish this stage.
So, is InternetGetConnectedState() the best approach?

Edited 6 Years Ago by Nfurman: n/a

This article has been dead for over six months. Start a new discussion instead.