29

I am using .NET, C# and WPF, and I need to check whether the connection is opened to a certain URL, and I can't get any code to work that I have found on the Internet.

I tried:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    IAsyncResult result = socket.BeginConnect("localhost/myfolder/", 80, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(3000, true);
    if (!success)
    {
        MessageBox.Show("Web Service is down!");
    }
    else
        MessageBox.Show("Everything seems ok");
}
finally
{
    socket.Close();
}

But I always get the message that everything is OK even if I shut down my local Apache server.

I also tried:

ing ping = new Ping();
PingReply reply;
try
{
    reply = ping.Send("localhost/myfolder/");
    if (reply.Status != IPStatus.Success)
        MessageBox.Show("The Internet connection is down!");
    else
        MessageBox.Show("Seems OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex.Message);
}

But this always gives an exception (ping seems to work only pinging the server, so localhost works but localhost/myfolder/ doesnt)

Please how to check the connection so it would work for me?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ragnar
  • 4,292
  • 4
  • 31
  • 41
  • Are you trying to verify that your connection is up (in which case Ping would work), or that a certain URL is accessible? – Gabe Mar 23 '11 at 13:36
  • Do you just need to check if the internet connection is up, or if your particular web service is up and running? They are potentially two different things. – Joe Mar 23 '11 at 13:37
  • That a particular web service is up and running – Ragnar Mar 23 '11 at 13:37
  • You are just checking that the connect eventually ends. – Felice Pollano Mar 23 '11 at 13:40
  • What kind of web services you are planning to use? I am doubting that there is one universal method to check all webservice types – Anton Semenov Mar 23 '11 at 13:56
  • web service available using http on port 80 – Ragnar Mar 23 '11 at 13:58
  • Possible duplicate of [How do I check for a network connection?](https://stackoverflow.com/questions/520347/how-do-i-check-for-a-network-connection) – T.Todua Sep 09 '19 at 11:11

8 Answers8

34

Many developers are solving that "problem" just by ping-ing Google.com. Well...? :/ That will work in most (99%) cases, but how professional is to rely work of Your application on some external web service?

Instead of pinging Google.com, there is an very interesting Windows API function called InternetGetConnectedState(), that recognizes whether You have access to Internet or not.

THE SOLUTION for this situation is:

using System;
using System.Runtime;
using System.Runtime.InteropServices;
 
public class InternetAvailability
{
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int description, int reservedValue);
 
    public static bool IsInternetAvailable( )
    {
        int description;
        return InternetGetConnectedState(out description, 0);
    }
}
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
  • 1
    In a test case where I am going through a proxy and the proxy is down and no browser pages load, the above method still returns true while there is technically no internet available. So this solution isn't the right one. I'm using a combination of the above AND connecting to my service :) – Rowan Aug 29 '16 at 20:04
  • does the "wininet.dll" exist to all windows versions? – gts13 May 02 '17 at 10:42
  • @user2048060 "wininet.dll" exists all windows version except `Windows XP and Windows Server 2003 R2 and earlier` Read more at : https://msdn.microsoft.com/en-us/library/windows/desktop/aa383630(v=vs.85).aspx – Anant Dabhi May 02 '17 at 10:58
  • 2
    @AnantDabhi thanks for the resource. In addition, I also found this function https://msdn.microsoft.com/en-us/library/windows/desktop/aa384346%28v=vs.85%29.aspx that does exactly what Rowan says. You can also add it in your response if you want. – gts13 May 04 '17 at 06:27
  • What if I want an event when internet goes down – John Demetriou Nov 08 '18 at 09:40
  • This solution is more fast than ping to Google. If you want to know, just try two codes in unit test. – Umut D. Oct 22 '21 at 06:42
23

In the end I used my own code:

private bool CheckConnection(String URL)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Timeout = 5000;
        request.Credentials = CredentialCache.DefaultNetworkCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}

An interesting thing is that when the server is down (I turn off my Apache) I'm not getting any HTTP status, but an exception is thrown. But this works good enough :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ragnar
  • 4,292
  • 4
  • 31
  • 41
  • 3
    If you want to check your HTTP Status, grab the `WebException` exception and see the `Status` property. There's also an item called `TimeOut`. – fa wildchild Jan 22 '13 at 01:27
  • 2
    In the end, you could just do this: `return (response.StatusCode == HttpStatusCode.OK);` – Alireza Noori Feb 14 '15 at 16:23
  • 1
    I used this method, most of times returns false even if I have internet connected and no issues in the website – amal50 Jun 15 '18 at 11:45
15

You can try this;

private bool CheckNet()
{
    bool stats;
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
    {
        stats = true;
    }
    else
    {
        stats = false;
    }
    return stats;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shujaat Abdi
  • 556
  • 1
  • 5
  • 11
15

Use this:

private bool CheckConnection()
{
    WebClient client = new WebClient();
    try
    {
        using (client.OpenRead("http://www.google.com"))
        {
        }
        return true;
    }
    catch (WebException)
    {
        return false;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • Though it would work, it is not correct, because we still are depending on a website rather than, the PC's internet connection. – Naresh Oct 28 '13 at 06:32
  • 3
    I have been using this for years, but then ran into an issue when one of our developers got locked out of google because he/she sent over 5000 requests in an hour to google, which flagger the application as a denial of service attack. – Rogala Jun 05 '15 at 14:43
  • I (and the users of my applications) use this method successfully. If you want to verify there is an internet connection, it's usually because you want to connect to a web server. The best way to make sure (1) there is internet and (2) the site you want is running a web server, is to open a WebClient, as above, but use the address you actually want instead of google.com. – Skyfish May 21 '22 at 19:38
8

I went through all the solutions. NetworkInterface.GetIsNetworkAvailable() doesn't check internet connection. It only check whether any network connection is available.

Ping is not reliable as in many network ping is turned off. Connecting to google with webclient is also not 100% reliable and it also has performance overhead if you use it too frequently.

Using Windows NLM API seems a better solution to me.

using NETWORKLIST;

namespace Network.Helpers
{
    public class InternetConnectionChecker
    {
        private readonly INetworkListManager _networkListManager;

        public InternetConnectionChecker()
        {
            _networkListManager = new NetworkListManager();
        }

        public bool IsConnected()
        {
            return _networkListManager.IsConnectedToInternet;
        }
        
    }
}

This is how to add it to project.

enter image description here

Mahbubur Rahman
  • 4,961
  • 2
  • 39
  • 46
7

I think this will be more accurate when it comes windows applications, Windows form or WPF apps, Instead of using WebClient or HttpWebRequest,

public class InternetChecker
{
    [System.Runtime.InteropServices.DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet()
    {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }

}

While calling write

if(InternetCheckerCustom.CheckNet())
{
  // Do Work 
}
else
{
  // Show Error MeassgeBox 
}
susant
  • 382
  • 3
  • 11
1

Here is a solution similar to Mahbubur Rahman, but using the COM interface directly an without the need to have a reference to Network List Manager 1.0 Type Library :

dynamic networkListManager = Activator.CreateInstance(
    Type.GetTypeFromCLSID(new Guid("{DCB00C01-570F-4A9B-8D69-199FDBA5723B}")));
    
bool isConnected = networkListManager.IsConnectedToInternet;
tigrou
  • 4,236
  • 5
  • 33
  • 59
0

Can we use ping just asking?

try
{
    System.Net.NetworkInformation.Ping ping = new Ping();

    //If you use DNS name as below it will give random time outs 
    //PingReply result = ping.Send("www.google.com");
   
    //INSTEAD USE IP ADDRESS LIKE BELOW IT WILL GIVE ACCURATE TIMEOUTS
    PingReply result = ping.Send("8.8.8.8");

    if (result.Status == IPStatus.Success)
        return true;
     return false;
}
catch
{
    return false;
}