Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

C-Sharp Code to Check if Internet Connection is Available or Not

In some of our applications it is necessary to connect to Internet. So before connecting to Internet it is necessary to check, whether your application has Internet access.

May be you are thinking to solve this problem just by ping -ing to google.com or any websites. Yes this will work in most of the cases, and it is also a simple, good and important method. But as an Application developer it is not the best method to do that.

So, how to do that? 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.

C# code to check internet availability :

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);
    }
}

And just call to static method IsInternetAvailable( ) in if loop. That's completed.


Conclusion :

I hope that this article would have helped you in Checking if Internet Connection is Available or Not. Your feedback and constructive contributions are always welcome.


No comments:

Post a Comment