我在程序中能调用系统中的ping吗?如果能我怎样获得它的返回值?(100分)

  • 主题发起人 主题发起人 lovesun
  • 开始时间 开始时间
用的直接ping代码吧,这里面有:
http://www.8421.org/download.php?id=106
 
up:
那个程序有点看不懂,能不能帮我写个简短的例子?
谢谢.
 
unit Ping;

interface

uses
Windows,Winsock,Sysutils;

Const
{ Exception Message }
SInitFailed = 'Winsock version error';
SInvalidAddr = 'Invalid IP Address';
SNoResponse = 'No Response';
STimeOut = 'Request TimeOut';

type
DWORD=LongWord;
THandle=LongWord;
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 IcmpCreateFile():THandle;stdcall external 'ICMP.dll';
function IcmpCloseHandle(Handle:THandle):Boolean;stdcall external 'ICMP.dll';
function IcmpSendEcho(Handle:THandle;
DestAddr:DWORD;
RequestData: Pointer;
RequestSize: Word;
RequestOptions: PIPOptionInformation;
ReplyBuffer: Pointer;
ReplySize: DWORD;
Timeout: DWORD): DWORD;stdcall external 'ICMP.dll';
procedure ValidCheck(); //要加到form .create
procedure FreeWinsock(); //要加到form.close
function PingServer(IPAddr:String;TimeOut:Word):boolean; //如果返回为false就是PING失败

var
hICMP:THandle;

implementation

procedure ValidCheck();
var
WSAData:TWSAData;
begin
if (WSAStartup($202,WSAData)<>0) then
raise Exception.Create(SInitFailed);
hIcmp:=IcmpCreateFile();
if hICMP=INVALID_HANDLE_VALUE then
raise Exception.Create('Create ICMP Failed');
end;

procedure FreeWinsock();
begin
IcmpCloseHandle(hIcmp);
WSACleanUP;
end;

function PingServer(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
GetMem(pIPAddr,Length(IPAddr)+1);
FillChar(pIPAddr^,Length(IPAddr)+1,0);
StrPCopy(pIPAddr,IPAddr);

FIPAddress := inet_addr(pIPAddr);

FreeMem(pIPAddr);

if FIPAddress=INADDR_NONE then
begin
result:=false;//Exit
exit;
end;


FSize := 40;
BufferSize := SizeOf(TICMPEchoReply) + FSize;
GetMem(pRevData,FSize);
GetMem(pIPE,BufferSize);

FillChar(pIPE^, SizeOf(pIPE^), 0);
pIPE^.Data := pRevData;
MyString := 'Ping Digital Data';
pReqData := PChar(MyString);
FillChar(IPOpt, Sizeof(IPOpt), 0);

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

if temp=0 then
begin
Result:=false;
exit;
end;

if pReqData^ = pIPE^.Options.OptionsData^ then
Result:=true
else
Result:=false;

FreeMem(pRevData);

FreeMem(pIPE);

end;



end.

//使用这
 
后退
顶部