Checking for internet connection in runtime

2.2k Views Asked by At

In which event or how can i check for internet connections while program is running? Scenario: program is running and suddenly internet connection goes off and a dialog opens "No internet access, changing connection string to central database". I tried this function, but im not sure in which event should i put so that it works all the time.

function TFK_Lib.CheckInternet: boolean;
begin
  ConnectedState := INTERNET_CONNECTION_MODEM;
  Result := InternetGetConnectedState(@ConnectedState, 0);
end;
2

There are 2 best solutions below

5
On

You can do a practical test and ping google.com. If I understood your question correctly I thinks its not a bad option. Code example:

class function TAuthUserFunctions.CheckInternet: boolean;
    var
     idtcp : TIdTCPClient;
    begin
      try
        idtcp := TIdTCPClient.Create(Nil);
        try
          idtcp.ReadTimeout := 2000;
          idtcp.ConnectTimeout := 2000;
          idtcp.Port := 80;
          idtcp.Host := 'google.com';
          idtcp.Connect;
          idtcp.Disconnect;
          Result := True;
        finally
          idtcp.Free;
        end;
      except
        Result := False;
      end;
    end;
0
On

You can use a timer to check (at a time period) the connection and show the dialog (as a modal so you can't do anything else).