如何从“ping -c 1 example.com”获得响应?

时间:2011-11-04 09:58:58

标签: perl

在BASH中我可以像这样ping服务器

for i in $MY_SERVER_LIST; do
   if ping -c 1 $i > /dev/null 2>&1; then
      # $i is alive
   fi
done

我想在Perl中做同样的事情,但我如何从

获得响应
my $response = `ping -c 1 google.com > /dev/null 2>&1`

问题

我如何在Perl中执行相同的操作,但不使用Net::Ping等任何包?

2 个答案:

答案 0 :(得分:4)

您对ping的exitcode感兴趣而不是输出;忘记$response并检查$?中的exitcode。

答案 1 :(得分:1)

我使用Net :: Ping!

use Net::Ping;
$p = Net::Ping->new();
print "$host is alive.\n" if $p->ping($host);
$p->close();
$p = Net::Ping->new("icmp");
$p->bind($my_addr); # Specify source interface of pings
foreach $host (@host_array)
{
print "$host is ";
print "NOT " unless $p->ping($host, 2);
print "reachable.\n";
sleep(1);
}
$p->close();

http://perldoc.perl.org/Net/Ping.html