delphi check internet connection

百般思念 提交于 2019-12-23 06:36:05

问题


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;

回答1:


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;



回答2:


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.




回答3:


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;


来源:https://stackoverflow.com/questions/22389242/delphi-check-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!