Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the Internet connection with .NET, C#, and WPF

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?

like image 779
Ragnar Avatar asked Mar 23 '11 13:03

Ragnar


People also ask

How do I check what my internet connection is?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.

How do I check if a network connection is available?

To check for an Internet connection in .NET, we can use GetIsNetworkAvailable method defined in the System.Net.NetworkInformation namespace. But it returns a Boolean value that denotes whether any network connection is available and does not say about Internet connectivity to a website or IP address or host .

How to check for an internet connection in a web application?

To check for an Internet connection in.NET, we can use GetIsNetworkAvailable method defined in the System.Net.NetworkInformation namespace. But it returns a Boolean value that denotes whether any network connection is available and does not say about Internet connectivity to a website or IP address or host.

How to detect that active connection is Wi-Fi or Ethernet in C #?

How to detect that active connection is Wi-Fi or Ethernet in C# .NET? 1 Check for Internet Connection, not for network availability Related 1722 Type Checking: typeof, GetType, or is?

How to check if local system has active internet connection?

The 'wininet' API can be used to check the local system has active internet connection or not. The namespace used for this is 'System.Runtime.InteropServices' and import the dll 'wininet.dll' using DllImport.


7 Answers

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);
    }
}
like image 197
Anant Dabhi Avatar answered Oct 04 '22 00:10

Anant Dabhi


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 :)

like image 31
Ragnar Avatar answered Oct 03 '22 22:10

Ragnar


Use this:

private bool CheckConnection()
{
    WebClient client = new WebClient();
    try
    {
        using (client.OpenRead("http://www.google.com"))
        {
        }
        return true;
    }
    catch (WebException)
    {
        return false;
    }
}
like image 37
Bala R Avatar answered Oct 03 '22 22:10

Bala R


You can try this;

private bool CheckNet()
{
    bool stats;
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
    {
        stats = true;
    }
    else
    {
        stats = false;
    }
    return stats;
}
like image 22
Shujaat Abdi Avatar answered Oct 03 '22 22:10

Shujaat Abdi


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 
}
like image 36
susant Avatar answered Oct 03 '22 23:10

susant


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

like image 40
Mahbubur Rahman Avatar answered Oct 03 '22 22:10

Mahbubur Rahman


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;
like image 34
tigrou Avatar answered Oct 03 '22 22:10

tigrou