views:

653

answers:

3

I wish to write a windows app which does something when I become disconnected from the internet. I was thinking of writing a very simple C#/Delphi app which simply polls every 20 seconds to see if I'm still connected.

If I have to poll I'd really like a solution other than trying to download a web page from the net. I can't assume that a download attempt failing means "not online" since there may be other apps eating up the internet bandwidth. Plus I'm sure constantly connecting/downloading from a particular site is going to get my IP blocked.

I'm sure there's a way to tell if you're online without downloading/connecting to a remote server but I'm not sure how.

+2  A: 

It looks like it can be done by using the method described here: http://www.csharphelp.com/archives3/archive499.html

John Boker
+1 for linking to C# source.
Ben Daniel
+3  A: 

Call the InternetGetConnectedState function. This knowledgebase article explains how to do it.

Greg Hewgill
+10  A: 

Beware that connected to the Internet does not really mean anything: what if you are connected to your ISP, but the backbone is down, or all the sites you want to access are in a country that went off the grid like recently? Having a connection does not mean you can do what you want.
Anyway, as stated before you can use the InternetGetConnectedState API to test that you have a valid Internet connection configured.
As an example, the following routine told me correctly I had a LAN Connection, but failed to detect that I had my ZoneAlarm firewall set to block "All Internet Activity", which means that you effectively lost all Internet connectivity.

Delphi routine:

procedure IsConnected;
var
  dwFlags: DWORD;
begin
  if InternetGetConnectedState(@dwFlags, 0) then
  begin
    if (dwFlags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM  then
      ShowMessage('Modem Connection')
    else
    if (dwFlags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then
      ShowMessage('LAN Connection')
    else
    if (dwFlags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
      ShowMessage('Connection thru Proxy')
    else
    if (dwFlags and INTERNET_CONNECTION_OFFLINE) = INTERNET_CONNECTION_OFFLINE then
      ShowMessage('Local system in offline mode')
    else
    if (dwFlags and INTERNET_CONNECTION_CONFIGURED) = INTERNET_CONNECTION_CONFIGURED then
      ShowMessage('Valid connection exists, but might or might not be connected')
  end
  else
    ShowMessage('Not Connected. Try to connect and risk of being prompted to dial into another Internet Service Provider.');
end;
François
Wow I did a double-take when I saw how much support this answer got. I'm not sure if this applies to my situation or not though. Basically my router keeps disconnecting and I want to turn it off and back on again using X10 commands if it becomes disconnected.
Ben Daniel