德尔福检查互联网连接

sta*_*rhu -3 delphi delphi-2010

我需要Delphi 2010的工作功能来检查是否有可用的Internet连接.

我说工作是因为到目前为止我尝试了4种不同的方法,例如http://delphi.about.com/b/2005/04/22/how-to-check-for-internet-connection-using-delphi-code.htm但是既没有奏效.

例如,一种方法总是回复说即使电缆不在电脑中也有互联网连接,另一种方法相反(它总是说没有连接).

     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;
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 16

唯一可靠的方法是尝试连接到某个地方的Internet上的真实服务器,看看它是成功还是失败.不要使用依赖OS状态信息的OS功能,因为这些数据很容易失去同步.


小智 6

添加您使用的单元“WinNet”。使用函数“InternetGetConnectedState”返回互联网状态和类型的值。见下文:

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;
Run Code Online (Sandbox Code Playgroud)

更新我较新的 Delphi 版本添加“wininet”作为使用类。