2

我正在编写一个返回给定主机的 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";
}

提前致谢!

4

1 回答 1

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";
于 2013-08-13T09:44:07.207 回答