How to Check if a Server is Alive in Perl Using Net::Ping
use Net::Ping;
sub pinghost {
my $host = shift;
my $type = shift || 'icmp';
my $port = shift || 7; # for syn ping
my $status;
my $p = Net::Ping->new($type);
if ($type eq 'icmp' or $type eq 'tcp') {
if ($p->ping($host, 10)) {
$status = 1;
} else {
$status = 0;
}
} elsif ($type eq 'syn') {
$p->port_number($port);
$p->ping($host, 10);
if ($p->ack) {
$status = 1;
} else {
$status = 0;
}
}
$p->close;
return $status;
}
Usage Examples:
# Performs standard ICMP ping (requires root privileges)
pinghost($host);
# Pings a specific TCP port (e.g., HTTP port 80) by sending a SYN and waiting for ACK (does not require root)
pinghost($host, 'syn', 80);
# Tries to connect to the peer's echo port (does not require root)
pinghost($host, 'tcp');
No comments:
Post a Comment