做个小程序想随时高效的判断网络是否 掉线 和 已经连接上 ,请问应该怎么处理?
网络上的答案就不要给了,全试了个遍,没一个考虑得全面且实用!
谢谢!

解决方案 »

  1.   

    除了ping外还有别的方法可行吗?
      

  2.   

    使用socket连接到服务器,如果连接不上说明网络断了
      

  3.   

    使用心跳机制,定时ping,判断。改变托盘图标。显示连接状态。 
      

  4.   

    第一步API IsNetworkAlive() 能返回当前网络连接状态。(仅连接状态哦)
       NETWORK_ALIVE_LAN  内网OK
       NETWORK_ALIVE_WAN  公网OK(仅限于类似ADSL拨号直连连接)第二步
      const ROUTE_TO_GOOGLE = $04040404;
      GetBestInterface(ROUTE_TO_GOOGLE, @dwInterfaceIndex);
      如果这个返回网络接口了,那说明有网卡可以通向Google,那基本说明网络OK了第三步
      还不放心的话,上PING吧
      

  5.   

    自己写心跳。
    现在的大型MMO游戏都这么做。
      

  6.   

    function Ping(IP:string):boolean; overload;//uses WinSock
    function Ping(IP:string):Boolean;
    const
      IcmpVersion=102;
      IcmpDLL='icmp.dll';
    type
      TIcmpCreateFile=function:THandle;stdcall;
      TIcmpCloseHandle=function(IcmpHandle:THandle):Boolean;stdcall;
      TIcmpSendEcho=function(IcmpHandle:THandle;
        DestinationAddress:DWORD;
        RequestData:Pointer;
        RequestSize:Word;
        RequestOptions:Pointer;
        ReplyBuffer:Pointer;
        ReplySize:DWord;
        Timeout:DWord
        ):DWord;stdcall;
    var
      hICMPdll:HModule;// Handle for ICMP.DLL
      hICMP:THandle;
      IcmpCreateFile:TIcmpCreateFile;
      IcmpCloseHandle:TIcmpCloseHandle;
      IcmpSendEcho:TIcmpSendEcho;
      wsa:TWSAData;
      rep:array[1..128] of byte;
      InAddr2:DWORD;//InAddr1: TInAddr;
      phe:PHostEnt;// HostEntry buffer for name lookup
      pac:PChar;
      dwRet:DWORD;
      bValidIP:Boolean;
    begin
      Result:=False;
      try
        if WSAStartup($101,wsa)<>0 then exit;
        bValidIP:=False;
        InAddr2:=0;
        phe:=GetHostByName(PChar(IP));
        if Assigned(phe) then
        begin
          pac:=phe^.h_addr_list^;
          if Assigned(pac) then
          begin
            InAddr2:=LongInt(PLongInt(phe^.h_addr_list^)^);
            bValidIP:=True;
          end;
        end;
        if bValidIP then
        begin
          hICMPdll:=LoadLibrary(icmpDLL);
          if hICMPdll>0 then
          begin
            @ICMPCreateFile:=GetProcAddress(hICMPdll,'IcmpCreateFile');
            @IcmpCloseHandle:=GetProcAddress(hICMPdll,'IcmpCloseHandle');
            @IcmpSendEcho:=GetProcAddress(hICMPdll,'IcmpSendEcho');
            if (@ICMPCreateFile<>nil)and(@IcmpCloseHandle<>nil)and(@IcmpSendEcho<>nil) then
            begin
              hICMP:=IcmpCreateFile;
              if hICMP<>INVALID_HANDLE_VALUE then
              begin
                dwRet:=IcmpSendEcho(hICMP,InAddr2,nil,0,nil,@rep,128,0);
                Result:=(dwRet<>0);
    //            if hICMP<>INVALID_HANDLE_VALUE then
                IcmpCloseHandle(hICMP);
              end;
             // if hICMPdll<>0 then
              FreeLibrary(hICMPdll);
            end;
          end;
        end;
      finally
        WSACleanup;
      end;
    end;