Bug*_*ddy 2 connection perl port tcp ping
我在 Linux 上使用 Perl 5,版本 30。我想检查服务器是否处于活动状态,我只对 ping 调用返回 true 或 false 感兴趣。这是我的(非工作)代码:
#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
my $pinger = Net::Ping->new();
if ($pinger->ping('google.com')) {
print 'alive\n';
} else {
print 'dead\n';
}
Run Code Online (Sandbox Code Playgroud)
代码应该可以工作(我认为)。但它每次都失败(返回“死”)每台服务器。如果我作为 sudo: 执行它也会失败sudo perl pingcheck.pl。(编辑:我不能使用 sudo在实践中。我只是为了排除故障而尝试它。)
我确实Net::Ping安装了:
$ cpan -l | grep Net::Ping
Net::Ping 2.71
Run Code Online (Sandbox Code Playgroud)
Perl 没有错误消息。
如果我在 bash 中做同样的事情,ping 会按预期工作:
$ ping -c 3 google.com
PING google.com (64.233.178.100) 56(84) bytes of data.
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=1 ttl=43 time=49.8 ms
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=2 ttl=43 time=49.8 ms
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=3 ttl=43 time=50.0 ms
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 49.754/49.846/50.011/0.116 ms
Run Code Online (Sandbox Code Playgroud)
$ ping -c 3 google.com
Run Code Online (Sandbox Code Playgroud)
这是在执行 ICMP ping。
my $pinger = Net::Ping->new();
if ($pinger->ping('google.com')) { ...
Run Code Online (Sandbox Code Playgroud)
这不是在执行 ICMP ping。从文档:
您可以选择六种不同的协议之一用于 ping。“tcp”协议是默认的。...使用“tcp”协议,ping() 方法尝试建立到远程主机的回显端口的连接。
现在回声服务几乎从不活动或端口被阻塞,因此将其用作端点通常不起作用。如果您要使用 Net::Ping 执行 ICMP ping,则它的工作方式与使用以下ping命令时一样:
my $pinger = Net::Ping->new('icmp');
if ($pinger->ping('google.com')) { ...
Run Code Online (Sandbox Code Playgroud)
请注意,这些都不适合确定主机是否已启动。ICMP ping 经常被阻止。相反,您应该检查是否可以连接到您要使用的特定服务:
# check if a connect to TCP port 443 (https) is possible
my $pinger = Net::Ping->new('tcp');
$pinger->port_number(443);
if ($pinger->ping('google.com')) { ...
Run Code Online (Sandbox Code Playgroud)