type
PIPOptionInformation = ^TIPOptionInformation;
TIPOptionInformation = record
TTL: Byte;
TOS: Byte;
Flags: Byte;
OptionsSize: Byte;
OptionsData: PChar;
end;
PIcmpEchoReply = ^TIcmpEchoReply;
TIcmpEchoReply = record
Address: DWORD;
Status: DWORD;
RTT: DWORD;
DataSize: Word;
Reserved: Word;
Data: Pointer;
Options: TIPOptionInformation;
end;
function Ping1(IPAddr: string;
Timeout: Word): Boolean;
var
IPOpt: TIPOptionInformation;
// IP Options for packet to send
FIPAddress: DWORD;
pReqData, pRevData: PChar;
pIPE: PIcmpEchoReply;
// ICMP Echo reply buffer
FSize: DWORD;
MyString: string;
FTimeOut: DWORD;
BufferSize: DWORD;
temp: Integer;
pIPAddr: Pchar;
begin
//get ip
GetMem(pIPAddr, Length(IPAddr) + 1);
ZeroMemory(pIPAddr, Length(IPAddr) + 1);
StrPCopy(pIPAddr, IPAddr);
//calc
FIPAddress := inet_addr(pIPAddr);
//free it
FreeMem(pIPAddr);
//valid check
if FIPAddress = INADDR_NONE then
begin
//result := SInvalidAddr;
//Exit
Result := False;
exit;
end;
// WSAAsyncGetHostByAddr()
//package size
FSize := 40;
BufferSize := SizeOf(TICMPEchoReply) + FSize;
GetMem(pRevData, FSize);
GetMem(pIPE, BufferSize);
//prepare data
FillChar(pIPE^, SizeOf(pIPE^), 0);
pIPE^.Data := pRevData;
MyString := 'Ping Digital Data';
pReqData := PChar(MyString);
FillChar(IPOpt, Sizeof(IPOpt), 0);
//max delieve geteway
IPOpt.TTL := 64;
//time out
FTimeOut := TimeOut;
//go!!!
temp := IcmpSendEcho(hICMP, //dll handle
FIPAddress, //target
pReqData, //data
Length(MyString), //data length
@IPOpt, //addree of ping option
pIPE, //
BufferSize, //pack size
FTimeOut);
//timeout value
//check result
if temp = 0 then
begin
//Result := 'Ping Addr:' + IPAddr + ' ' + SNoResponse;
Result := False;
exit;
end;
if pReqData^ = pIPE^.Options.OptionsData^ then
begin
//show result
{ Result := ('Reply from:' + PChar(IPAddr) + ' '
+ 'bytes:' + IntToStr(pIPE^.DataSize) + ' '
+ 'tims:' + IntToStr(pIPE^.RTT) + 'ms '
+ 'TTL:' + intToStr(pIPE^.Options.TTL));
}
Result := True;
end;
//clear memory
FreeMem(pRevData);
FreeMem(pIPE);
end;
使用方法:if Ping1('192.168.0.1', 300) then
//成功