What is the best way to check for Internet connectivity using .NET?
public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
try
{
url ??= CultureInfo.InstalledUICulture switch
{
{ Name: var n } when n.StartsWith("fa") => // Iran
"http://www.aparat.com",
{ Name: var n } when n.StartsWith("zh") => // China
"http://www.baidu.com",
_ =>
"http://www.gstatic.com/generate_204",
};
var request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = timeoutMs;
using (var response = (HttpWebResponse)request.GetResponse())
return true;
}
catch
{
return false;
}
}
C# checking Internet connection
a little shorter version:
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
catch
{
return false;
}
}
Another option is:
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success) {
// presumably online
}
You can find a broader discussion here
check internet connection available or not in c#
You can check whether internet is available or not like this:
ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile == null)
{
//logic ....
}
if (internetConnectionProfile != null)
{
this.IsInternetAvailable = internetConnectionProfile.GetNetworkConnectivityLevel() ==
NetworkConnectivityLevel.InternetAccess;
if (internetConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)// Connection is not a Wi-Fi connection.
{
var isRoaming = internetConnectionProfile.GetConnectionCost().Roaming;
//user is Low on Data package only send low data.
var isLowOnData = internetConnectionProfile.GetConnectionCost().ApproachingDataLimit;
//User is over limit do not send data
var isOverDataLimit = internetConnectionProfile.GetConnectionCost().OverDataLimit;
IsWifiConnected = true;
}
else //Connection is a Wi-Fi connection. Data restrictions are not necessary.
{
IsWifiConnected = true;
}
}
How to check the Internet connection with .NET, C#, and WPF
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 :)
How do I check for a network connection?
You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
How to check internet connectivity type in Universal Windows Platform
1. Check Internet Connection Availability
To check whether any network connection is established or not use GetIsNetworkAvailable
method of NetworkInterface
class.
bool isNetworkConnected = NetworkInterface.GetIsNetworkAvailable();
GetIsNetworkAvailable() -
Summary: Indicates whether any network connection is available.
Returns:true
if a network connection is available; otherwise,false
.
2. Check Internet Connection Availability via WWLN (WiFi)
To check whether internet connected via WWAN use IsWlanConnectionProfile
property of ConnectionProfile
class
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
bool isWLANConnection = (InternetConnectionProfile == null)?false:InternetConnectionProfile.IsWlanConnectionProfile;
IsWlanConnectionProfile
Summary: Gets a value that indicates if connection profile is a WLAN (WiFi) connection. This determines whether or not
WlanConnectionProfileDetails is null.
Returns: Indicates if the connection profile represents a WLAN (WiFi) connection.
3. Check Internet Connection Availability via WWAN (Mobile)
To check whether internet connected via WWAN use IsWwanConnectionProfile
property ofConnectionProfile
class
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
bool isWLANConnection = (InternetConnectionProfile == null)?false:InternetConnectionProfile.IsWwanConnectionProfile;
IsWwanConnectionProfile
Summary: Gets a value that indicates if connection profile is a WWAN (mobile) connection. This determines whether or not WwanConnectionProfileDetails is null.
Returns: Indicates if the connection profile represents a WWAN (mobile) connection.
Reference
Hippiehunter Answer
4. Check Metered network
To check whether Internet reachable via a metered connection or not, use GetConnectionCost
method on NetworkInterface
class.
var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();
if (connectionCost.NetworkCostType == NetworkCostType.Unknown
|| connectionCost.NetworkCostType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}
Reference (More detailed answer here)
1. How to manage metered network cost constraints - MSDN
2. NetworkCostType Enum - MSDN
5. Manage network availability changes
To sense the significant network availability changes, use eventNetworkStatusChanged
of NetworkInformation
class
// register for network status change notifications
networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);
if (!registeredNetworkStatusNotif)
{
NetworkInformation.NetworkStatusChanged += networkStatusCallback;
registeredNetworkStatusNotif = true;
}
async void OnNetworkStatusChange(object sender)
{
// get the ConnectionProfile that is currently used to connect to the Internet
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (InternetConnectionProfile == null)
{
await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Not connected to Internet\n", NotifyType.StatusMessage);
});
}
else
{
connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser(connectionProfileInfo, NotifyType.StatusMessage);
});
}
internetProfileInfo = "";
}
References
Check Internet Connectivity - developerinsider.co
How to manage network connection events and changes in availability - MSDN
How to retrieve network connection information- MSDN
Hope it helpful to someone.
How to check if internet connectivity available or not in C#
Why not just try to perform a very cheap query on the database? Indeed, you could create a stored procedure for exactly this purpose - it might even give some version information back, etc.
After all, the important thing isn't whether a ping works, or whether the client can go to other machines: the important thing is whether you can talk to the database or not. So test exactly that.
As for what error message is presented to the user - surely that's under your control, so make sure you give appropriate information.
Checking network status in C#
If you just want to check if the network is up then use:
bool networkUp
= System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
To check a specific interface's status (or other info) use:
NetworkInterface[] networkCards
= System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
To check the status of a remote computer then you'll have to connect to that computer (see other answers)
Related Topics
Making Entity Class Closed for Changes
Passing Variable Between Winforms
How to Run a Simple Bit of Code in a New Thread
How to Get the Client's Ip Address in ASP.NET MVC
What Is the Purpose of the VShost.Exe File
Validateantiforgerytoken Purpose, Explanation and Example
How to Make Databinding Type Safe and Support Refactoring
Using Side-By-Side Assemblies to Load the X64 or X32 Version of a Dll
How to Check If Wpf Is Currently Executing in Design Mode or Not
Difference Between String and Stringbuilder in C#
How to Get Only Time from Date-Time C#
How to Change the Color of Progressbar in C# .Net 3.5
Getting the Current Tab's Url from Google Chrome Using C#