delphidelphi-2010

delphi check internet connection


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;

Solution

  • 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.