How to check the Internet connection with .NET, C#, and WPF

Many developers are solving that “problem” just by ping-ing Google.com. Well…? :/ That will work in most (99%) cases, but how professional is to rely work of Your application on some external web service?

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.

THE SOLUTION for this situation is:

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

Leave a Comment