我正在编写一个小脚本,它返回给定主机的ping时间。到目前为止,一切都按预期工作,但希望能够查看丢失的数据包数量。
在Windows命令提示符下运行标准ping命令时,您会得到如下内容:
Ping-statistic for 173.194.70.138:
Packets: Sent = 4, Received = 4, Lost = 0 (0%)
每次数据包丢失时如何进行perl计数?有没有办法在perl中调用windows命令?
我目前的代码如下:
#!/usr/bin/perl
use warnings;
use strict;
use Time::HiRes;
use Net::Ping;
use vars qw($ARGV $ret $duration $ip);
my $host = $ARGV[0] or print "Usage is: $0 host [timeout]\n" and exit 1;
my $timeout = $ARGV[1] || 5;
my $p = Net::Ping->new('icmp', $timeout);
if ($p->ping($host)) {
$p->hires();{
($ret, $duration, $ip) = $p->ping($host);
printf("$host [ip: $ip] is online (packet return time: %.2f ms)\n", 1000*$duration);
}
$p->close();
}else{
print "No such host, timeout of $timeout seconds reached\n";
}
提前致谢!
答案 0 :(得分:1)
如果无法找到主机名或IP号码有问题,则返回的成功标志将为undef。否则,如果主机可访问,则成功标志为1,如果不可达,则为0。
因此$p->ping
可以返回undef
,1
或0
my $lost = 0;
my $n = 10;
while ($n--) {
# die if ping returns undef
my $ok = $p->ping($host) // die "No such host, timeout of $timeout seconds reached\n";
$lost++ if !$ok;
}
print "$lost lost packets\n";