Wednesday, May 11, 2011

sever alive checking in perl using Net::Ping in Linux or Mac system

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;
}

__END__

call it:

pinghost($host); # do the same stuff as unix's ping command with ICMP,
requires root
pinghost($host,'syn',80); # not requires root,can ping to a special TCP
port (i.e, the http port), send a syn and wait for ack.
pinghost($host,'tcp'); # not requires root, try to connect to peer's

echo port

No comments: