我用Indy 的 TIdIcmpClient组件做了个ping程序。用于邮件服务器,测试目的主机是否ping得通。
但是测试时,如果输入错误的域名,如21cn.org,执行时就出错,提示socket error。如何使程序不出错,只需要得到是否ping得通的是非答案。
我的测试代码如下:
procedure TForm1.button1Click(Sender: TObject);
var
i: integer;
begin
lstReplies.Items.Clear; ICMP.OnReply := ICMPReply;
ICMP.ReceiveTimeout := 1000;
button1.Enabled:= False; try
ICMP.Host := edtHost.Text;
for i := 1 to 4 do
begin
ICMP.Ping;
Application.ProcessMessages;
end;
except
button1.Enabled := True;
end; button1.Enabled := True;end;
procedure TForm1.ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus);
var
sTime: string;
begin
// TODO: check for error on ping reply (ReplyStatus.MsgType?)
if (ReplyStatus.MsRoundTripTime = 0) then sTime := '<1'
else sTime := '='; lstReplies.Items.Add(Format('%d bytes from %s: icmp_seq=%d ttl=%d time%s%d ms',
[ReplyStatus.BytesReceived,
ReplyStatus.FromIpAddress,
ReplyStatus.SequenceId,
ReplyStatus.TimeToLive,
sTime,
ReplyStatus.MsRoundTripTime]));end;
但是测试时,如果输入错误的域名,如21cn.org,执行时就出错,提示socket error。如何使程序不出错,只需要得到是否ping得通的是非答案。
我的测试代码如下:
procedure TForm1.button1Click(Sender: TObject);
var
i: integer;
begin
lstReplies.Items.Clear; ICMP.OnReply := ICMPReply;
ICMP.ReceiveTimeout := 1000;
button1.Enabled:= False; try
ICMP.Host := edtHost.Text;
for i := 1 to 4 do
begin
ICMP.Ping;
Application.ProcessMessages;
end;
except
button1.Enabled := True;
end; button1.Enabled := True;end;
procedure TForm1.ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus);
var
sTime: string;
begin
// TODO: check for error on ping reply (ReplyStatus.MsgType?)
if (ReplyStatus.MsRoundTripTime = 0) then sTime := '<1'
else sTime := '='; lstReplies.Items.Add(Format('%d bytes from %s: icmp_seq=%d ttl=%d time%s%d ms',
[ReplyStatus.BytesReceived,
ReplyStatus.FromIpAddress,
ReplyStatus.SequenceId,
ReplyStatus.TimeToLive,
sTime,
ReplyStatus.MsRoundTripTime]));end;
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货