tags:

views:

931

answers:

8

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.

+7  A: 

I'm not a c# developer but in C++ you can use the Win32 API (specifically from Wininet.dll) like this:

bool IsInternetConnected( void )
{
    DWORD dwConnectionFlags = 0;

    if( !InternetGetConnectedState( &dwConnectionFlags, 0 ) )
        return false;

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

    return true;
}

I assume this is trivially turned into c#

QAZ
+1  A: 

A guess at Internet connectivity would be network availability, at NetworkInterface.GetIsNetworkAvailable(). The events on NetworkChange can tell you when it changes. Both classes are in the System.Net.NetworkInformation namespace.

Of course, you won't know if the Internet is really available until you try to connect to something.

Barry Kelly
+8  A: 

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(long flags,long reserved);
sbeskur
Thanks for porting my answer to c# :)
QAZ
There is a bug in your translation of InternetGetConnectedState. See below for a translation
JaredPar
A: 

I found this code elsewhere, but really want to know if there is a better way.

HttpWebRequest req;
HttpWebResponse resp;
try
{
    req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
    resp = (HttpWebResponse)req.GetResponse();

    if(resp.StatusCode.ToString().Equals("OK"))
    {
        Console.WriteLine("its connected.");
    }
    else
    {
        Console.WriteLine("its not connected.");
    }
}
catch(Exception exc)
{
    Console.WriteLine("its not connected.");
}

I like the idea of being able to monitor if the connection is lost via the NetworkChange event thrown by NetworkInterface. My app is for use by inexperienced users, on notebooks, where Internet connectivity is erratic (often in the Australian Outback).

Stuart Helwig
A: 

http://www.csharphelp.com/archives3/archive499.html

Also, scroll past the experts-exchange links at: http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=13045, and you'll see some suggestions.

Also, if you are game for the My namespace from VB.Net (which you can link to, btw), My.Computer.Network.IsAvailable is the simplest solution.

torial
+4  A: 

sbeskur's response has a bug in the translation of InternetGetConnectedState. The parameters are both DWORD's (first one is an LPDWORD). Both of these translate to int's in C# (technically, uint but int will work for most scenarios).

Correct translation below.


[DllImport("wininet.dll", SetLastError=true)] 
public static extern bool InternetGetConnectedState(out int flags,int reserved);
JaredPar
+1  A: 

InternetGetConnected state is step one in establishing that you are connected to a network. In order to determine if you have an internet connection one technique is to use the IPHelper api to send an ARP (address resolution protocol) request for some server on the internet.

Jim In Texas
Besides the fact that not everyone is connected to an Ethernet network, you cannot send ARP requests outside of your own broadcast domain. In the best case you'll have an edge gateway respond to your request with its own MAC address, which gains you nothing.
Mihai Limbășan
Correct me if I'm wrong, but if I depend on pinging then I run the risk that either a firewall or the server I'm pinging will filter pings. On the other hand if I arp_request(google.com) and I get a valid response then I know I can get out on the net. For this purpose that's all we want.
Jim In Texas
+1  A: 

Ping google.com (or a list of well-known hosts) or try actually performing one of the functions (in a structural sense) for which your application requires Internet connectivity. There is no way, on any operating system, to truly determine whether or not Internet connectivity is functional without actually trying to communicate, as opposed to the operating system's view on what constitutes "available".

Mihai Limbășan