开发者

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

开发者 https://www.devze.com 2023-02-19 09:20 出处:网络
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 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?


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);
    }
}


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


Use this:

private bool CheckConnection()
{
    WebClient client = new WebClient();
    try
    {
        using (client.OpenRead("http://www.google.com"))
        {
        }
        return true;
    }
    catch (WebException)
    {
        return false;
    }
}


You can try this;

private bool CheckNet()
{
    bool stats;
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
    {
        stats = true;
    }
    else
    {
        stats = false;
    }
    return stats;
}


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.

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


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 
}


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;


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消