Delphi 快速Ping局域网IP或网站并返回结果的方式

Delphi 快速Ping局域网IP并返回结果的方式

引入单元:WinSock;

function PingHost(HostIP: string): boolean;
type
  PIPOptionInformation = ^TIPOptionInformation;
  TIPOptionInformation = packed record
    TTL: Byte;
    TOS: Byte;
    Flags: Byte;
    OptionsSize: Byte;
    OptionsData: pchar;
  end;
  PIcmpEchoReply = ^TIcmpEchoReply;
  TIcmpEchoReply = packed record
    Address: DWORD;
    Status: DWORD;
    RTT: DWORD;
    DataSize: WORD;
    Reserved: WORD;
    Data: Pointer;
    Options: TIPOptionInformation;
  end;
  TIcmpCreateFile = function: THandle; stdcall;
  TIcmpCloseHandle = function(IcmpHandle: THandle): boolean; stdcall;
  TIcmpSendEcho = function(IcmpHandle: THandle; DestinationAddress: DWORD; RequestData: Pointer; RequestSize: WORD; RequestOptions: PIPOptionInformation; ReplyBuffer: Pointer; ReplySize: DWORD; Timeout: DWORD): DWORD; stdcall;
var
  hICMP: THandle;
  hICMPdll: THandle;
  IcmpCreateFile: TIcmpCreateFile;
  IcmpCloseHandle: TIcmpCloseHandle;
  IcmpSendEcho: TIcmpSendEcho;
  pIPE: PIcmpEchoReply; //   ICMP   Echo   reply   buffer
  FIPAddress: DWORD;
  FSize: DWORD;
  FTimeOut: DWORD;
  BufferSize: DWORD;
  pReqData, pRevData: pchar;
  MyString: string;
begin
  result := false;
  hICMPdll := LoadLibrary('icmp.dll');
  if hICMPdll = 0 then
    Exit;
  @IcmpCreateFile := GetProcAddress(hICMPdll, 'IcmpCreateFile');
  @IcmpCloseHandle := GetProcAddress(hICMPdll, 'IcmpCloseHandle');
  @IcmpSendEcho := GetProcAddress(hICMPdll, 'IcmpSendEcho');
  hICMP := IcmpCreateFile;
  if (hICMP = INVALID_HANDLE_VALUE) then Exit;
  //uses winsock;
  FIPAddress := inet_addr(pchar(HostIP)); //Delphi xe:  inet_addr(PANSIChar(ansistring(HostIP)));
  MyString := 'Hello TaoRoy'; //send data buffer
  pReqData := pchar(MyString);
  FSize := 40; //receive data buffer
  BufferSize := SizeOf(TIcmpEchoReply) + FSize;
  GetMem(pIPE, BufferSize);
  FillChar(pIPE^, SizeOf(pIPE^), 0);
  GetMem(pRevData, FSize);
  pIPE^.Data := pRevData;
  FTimeOut := 50; //超时间隔毫秒
  try
    result := IcmpSendEcho(hICMP, FIPAddress, pReqData, Length(MyString), nil, pIPE, BufferSize, FTimeOut) > 0;
  finally
    IcmpCloseHandle(hICMP);
    FreeLibrary(hICMPdll);
    FreeMem(pRevData);
    FreeMem(pIPE);
  end;
end;

示例:

var
  b:boolean;
begin    
  b:=PingHost('192.168.0.2');
  if b then  ShowMessage('已连接') else ShowMessage('未连接') ;

  b:=PingHost('www.baidu.com');
  if  then  ShowMessage('True') else ShowMessage('False') ;
end;

 

 

 

创建时间:2021.05.11  更新时间:

posted on 2021-05-11 17:08  滔Roy  阅读(901)  评论(0编辑  收藏  举报

导航