Dec 20

With the increase in Web Enabled software designs, it’s becoming more and more important to know when a client machine is actually connected to the Internet, before taking some action. I ran into this situation recently myself, and thought I would display my solution in the hopes it helps a struggling code-head out there.

I read, tried and experimented with a number of solutions with varying degrees of success. The route I choose was one that allows me to detect a connection with a fair degree of accuracy.

I test for a valid connection (just before I am about to take some action that requires the Internet) by trying to open a known URL and validate the returned handle is not NIL.

NOTE : in D7 some constants were not declared in WinInet.pas so you might have to add them to your routine.


uses WinInet;
function IsConnected: Boolean;
const
//:[ Local system has a valid connection to the Internet, but it might or might not be currently connected.
INTERNET_CONNECTION_CONFIGURED = $40;
//:[  Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_LAN = $02;
//:[  Local system uses a modem to connect to the Internet
INTERNET_CONNECTION_MODEM = $01;
//:[  Local system is in offline mode.
INTERNET_CONNECTION_OFFLINE = $20;
//:[  Local system uses a proxy server to connect to the Internet
INTERNET_CONNECTION_PROXY = $04;
// Local system has RAS installed.
INTERNET_RAS_INSTALLED = $10;
var
InetState: DWORD;
hHttpSession, hReqUrl: HInternet;
begin
Result := InternetGetConnectedState(@InetState, 0);
if (Result and (InetState and INTERNET_CONNECTION_CONFIGURED = INTERNET_CONNECTION_CONFIGURED) ) then
begin
//:[ So far we ONLY know there's a valid connection, so see if we can grab a known URL
hHttpSession := InternetOpen( PChar(Application.Title), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hReqUrl := InternetOpenURL(hHttpSession, 'http://www.google.com', nil, 0,0,0);
Result := hReqUrl <> nil;
InternetCloseHandle(hReqUrl);
finally
InternetCloseHandle(hHttpSession);
end;
end
else
if (InetState and INTERNET_CONNECTION_OFFLINE = INTERNET_CONNECTION_OFFLINE) then
Result := False; //:[ We know for sure we are offline so return false
end;

Leave a Reply