Check Internet Connection In C# and .NET

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. 
  1. ...  
  2. using System.Net.NetworkInformation;  
  3. ...  
  4. public bool IsConnectedToInternet()  
  5. {  
  6. string host = http://www.c-sharpcorner.com;  
  7. bool result = false;  
  8. Ping p = new Ping();  
  9. try  
  10. {  
  11. PingReply reply = p.Send(host, 3000);  
  12. if (reply.Status == IPStatus.Success)  
  13. return true;  
  14. }  
  15. catch { }  
  16. return result;  
  17. }  
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. 
  1. using System ;  
  2. using System.Runtime ;  
  3. using System.Runtime.InteropServices ;  
  4. public class InternetCS  
  5. {  
  6. //Creating the extern function...  
  7. [DllImport("wininet.dll")]  
  8. private extern static bool InternetGetConnectedState( out int Description, int ReservedValue ) ;  
  9. //Creating a function that uses the API function...  
  10. public static bool IsConnectedToInternet( )  
  11. {  
  12. int Desc ;  
  13. return InternetGetConnectedState( out Desc, 0 ) ;  
  14. }  
  15. }  


Similar Articles