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?
Solution 1:
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);
}
}
Solution 2:
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 :)