Reputation: 401
I need a working function for Delphi 2010 to check if there is Internet connection available.
I say working because so far I tried 4 different methods e.g. http://delphi.about.com/b/2005/04/22/how-to-check-for-internet-connection-using-delphi-code.htm but neither worked.
For example one method alway gave back that there was internet connection even when the cable was not in the pc, the other the opposite (it always said there was no connection).
procedure TForm1.Button1Click(Sender: TObject) ;
function FuncAvail(_dllname, _funcname: string;
var _p: pointer): boolean;
{return True if _funcname exists in _dllname}
var _lib: tHandle;
begin
Result := false;
if LoadLibrary(PChar(_dllname)) = 0 then exit;
_lib := GetModuleHandle(PChar(_dllname)) ;
if _lib <> 0 then begin
_p := GetProcAddress(_lib, PChar(_funcname)) ;
if _p <> NIL then Result := true;
end;
end;
{
Call SHELL32.DLL for Win < Win98
otherwise call URL.dll
}
{button code:}
var
InetIsOffline : function(dwFlags: DWORD):
BOOL; stdcall;
begin
if FuncAvail('URL.DLL', 'InetIsOffline',
@InetIsOffline) then
if InetIsOffLine(0) = true
then ShowMessage('Not connected')
else ShowMessage('Connected!') ;
end;
Upvotes: -2
Views: 21298
Reputation: 1
I found that the best way is to use Indy TIdIcmpClient.
function fnHasInternet: Boolean;
var iPing: TIdIcmpClient;
begin
try
iPing := TIdIcmpClient.Create;
iPing.ReceiveTimeout := 500;
iPing.Host := 'google.com';
iPing.Ping();
Result := True;
iPing.Free;
except
Result := False;
iPing.Free;
end;
end;
Upvotes: -1
Reputation: 334
Add in your uses the unit "WinNet". With the function "InternetGetConnectedState" return a value for internet state and type. See below:
function YourFunctionName : boolean;
var
origin : cardinal;
begin
result := InternetGetConnectedState(@origin,0);
//connections origins by origin value
//NO INTERNET CONNECTION = 0;
//INTERNET_CONNECTION_MODEM = 1;
//INTERNET_CONNECTION_LAN = 2;
//INTERNET_CONNECTION_PROXY = 4;
//INTERNET_CONNECTION_MODEM_BUSY = 8;
end;
update i newer Delphi versions add "wininet" as uses class.
Upvotes: 7
Reputation: 41
You can use the TIdHTTP
component:
function TMainF.isInternetConnection: Boolean;
begin
try
IdHTTP.Get('http://www.svtech.cz');
except
on E: Exception do begin
if not (E is EIdHTTPProtocolException) then begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
Upvotes: 4
Reputation: 595295
The only reliable method is to attempt to connect to a real server on the Internet somewhere and see if it succeeds or fails. Don't use OS functions that rely on OS state information, because that data can easily get out of sync.
Upvotes: 18