13

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.

ICR
  • 13,896
  • 4
  • 50
  • 78
Stuart Helwig
  • 9,318
  • 8
  • 51
  • 67

8 Answers8

15

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); 
sbeskur
  • 2,260
  • 23
  • 23
10

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
  • 733,204
  • 149
  • 1,241
  • 1,454
9

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
  • 4,870
  • 6
  • 36
  • 50
2

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
  • 9,318
  • 8
  • 51
  • 67
1

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.

Druid
  • 6,423
  • 4
  • 41
  • 56
Barry Kelly
  • 41,404
  • 5
  • 117
  • 189
1

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
  • 1,524
  • 4
  • 20
  • 31
  • 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 Oct 12 '08 at 13:21
  • 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 Oct 16 '08 at 16:27
1

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
  • 64,368
  • 4
  • 48
  • 59
0

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
  • 13,085
  • 9
  • 62
  • 89