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;
}
}
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 :)
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
Any new method on checking internet connectivity using .NET?
If you're checking for internet connectivity, you probably have a reason... meaning you're looking to use some specific web resource. So check against that resource.
Even better, don't check at all. Internet services can go up or down at any moment... including the moment in between when you run your check and when you try to use the service. That means anything you do has to be able to handle failure anyway. So just don't run the check; put the work into your exception handler instead.
I know that may sound slow, or strange to use exception handling for flow control. But the main reason not to use exceptions for flow control is it's nearly the slowest thing you can do in all of computer science. You know what's even worse? Waiting for network packets to travel half way around the world or timeout, that's what.
In the rare case when you just want to show general internet status to the user, you can do it the same way Microsoft does, and use www.msftncsi.com
.
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 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
C# How to check internet connection in realiable and not block UI?
If you can't use a BackgroundWorker and you're targeting .NET 4.5 you can wrap that method inside a Task.
public static Task<bool> CheckInternetConnectionAsync( )
{
return Task<bool>.Run( ( ) => {
try
{
using ( var client = new WebClient( ) )
using ( var stream = client.OpenRead( "http://www.google.com" ) )
{
return true;
}
}
catch
{
return false;
}
} );
}
And whenever you need to check for internet connection do it like this ...
static async void CheckInternetConnection( )
{
//just an example how to read a value from Task
bool hasConnection = await CheckInternetConnectionAsync( );
}
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.
Related Topics
How to Get the Ip Address of the Server on Which My C# Application Is Running On
Pass Array Parameter in Sqlcommand
SQL Data Reader - Handling Null Column Values
Why Must "Stride" in the System.Drawing.Bitmap Constructor Be a Multiple of 4
Difference Between Null and System.Dbnull.Value
Why Doesn't C# Infer My Generic Types
Convert Linq Expression "Obj =≫ Obj.Prop" into "Parent =≫ Parent.Obj.Prop"
Access the Current Httpcontext in ASP.NET Core
Is There Any Significant Difference Between Using If/Else and Switch-Case in C#
Splash Screen Waiting Until Thread Finishes
Make a Borderless Form Movable
Odbcconnection Returning Chinese Characters as ""
How to Create Linq Expression Tree to Select an Anonymous Type
How to Get the List of Open File Handles by Process in C#
Why Does Adding a New Value to List≪≫ Overwrite Previous Values in the List≪≫