Delphi通过ICMP检测与远程主机连接

{ ping IP 地址(返回false or true) 2015-03-23}
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;
  FIPAddress:=inet_addr(PChar(HostIP));
  MyString := 'Hello,World';                                 //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:=500;
  try
    Result:=IcmpSendEcho(hICMP, FIPAddress,pReqData,
    Length(MyString),nil,pIPE,BufferSize,FTimeOut)>0;
  finally
    IcmpCloseHandle(hICMP);
    FreeLibrary(hICMPdll);
    FreeMem(pRevData);
    FreeMem(pIPE);
  end;
end;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值