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 make sure we also have Internet access, the reliable method is to attempt to ping an IP address.
The Ping class in .NET can be used to ping an IP using the Send method. The host can also be a URL. For example, this code snippet pings c-sharpcorner.com.
- ...
- using System.Net.NetworkInformation;
- ...
- public bool IsConnectedToInternet()
- {
- string host = http://www.c-sharpcorner.com;
- bool result = false;
- Ping p = new Ping();
- try
- {
- PingReply reply = p.Send(host, 3000);
- if (reply.Status == IPStatus.Success)
- return true;
- }
- catch { }
- return result;
- }
Or we can use a simple API function InternetGetConnectedState. This function takes two arguments:
The first one is an integer used with out keyword, which means that after calling the function, the variable will contain an integer that describes the connection state.
The second one is a reserved variable that must be set to 0.
- using System ;
- using System.Runtime ;
- using System.Runtime.InteropServices ;
- public class InternetCS
- {
- //Creating the extern function...
- [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 ) ;
- }
- }

Dharmendra Kumar PanditPosted Aug 23, 2019, 9:29 PM
Nice article .....
Bhuban MagarPosted Jul 6, 2018, 12:32 AM
If Internet is connected but network showing Limited instead of connected.what will be the result? using InternetGetConnectedState().
Pacacio SurielPosted Nov 21, 2017, 3:35 PM
Good Article Mr. Tomar.
Deco GecoPosted Aug 18, 2016, 8:54 PM
Seem
Deco GecoPosted Aug 18, 2016, 8:54 PM
Mine doesn't deem to like variable ping. yes I have typed using System.Net...
Suvendu GiriPosted Apr 29, 2015, 6:38 AM
Good article but consider adding more little explainantion would help others and also add advantages/disadvantages, comparision etc.
Angélica OrtegaPosted Apr 28, 2014, 7:48 PM
Hi would this work for Windows Mobile 6.5 ?
Dhruv ShahPosted Jul 19, 2013, 4:37 PM
Return value of desc is 81 and 82 for connected and disconnected ???
shweta parikhPosted Feb 16, 2009, 3:59 AM
hi i want to ask where should i put this code? nd i want to display my own error message.
wrleiPosted Feb 11, 2009, 3:01 AM
string host = http://www.c-sharpcorner.com should be string host = "http://www.c-sharpcorner.com", I test this URL is successful! but www.google.com is false, Do u know reason?