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?
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.
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 .
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# .NET? 1 Check for Internet Connection, not for network availability Related 1722 Type Checking: typeof, GetType, or is?
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.
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 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
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With