Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine if an Internet connection is available for your WinForms App?

Tags:

c#

.net

winforms

What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.

like image 259
Stuart Helwig Avatar asked Oct 11 '08 22:10

Stuart Helwig


1 Answers

The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:

NetworkInterface.GetIsNetworkAvailable() 

Here is a C# translation of Steve's code that seems to be pretty good:

private static int ERROR_SUCCESS = 0;
public static bool IsInternetConnected() {
    long dwConnectionFlags = 0;
    if (!InternetGetConnectedState(dwConnectionFlags, 0))
        return false;

    if(InternetAttemptConnect(0) != ERROR_SUCCESS)
        return false;

    return true;
}


 [DllImport("wininet.dll", SetLastError=true)]
 public static extern int InternetAttemptConnect(uint res);


 [DllImport("wininet.dll", SetLastError=true)]
  public static extern bool InternetGetConnectedState(out int flags,int reserved); 
like image 154
sbeskur Avatar answered Oct 16 '22 05:10

sbeskur