Pinging a Machine

Problem

You want to test whether a machine is alive. Network and system monitoring software often use the ping program as an indicator of availability.

Solution

Use the standard Net::Ping module:

use Net::Ping;

$p = Net::Ping->new()
    or die "Can't create new ping object: $!\n";
print "$host is alive" if $p->ping($host);
$p->close;

Discussion

Testing whether a machine is up isn’t as easy as it sounds. It’s not only possible but it’s also unpleasantly common for machines to respond to the ping command and have no working services. It’s better to think of a ping as testing whether a machine is reachable, rather than whether the machine is doing its job. To check the latter, you must try to use its services (telnet, FTP, web, NFS, etc).

In the form shown in the Solution, Net::Ping attempts to connect to the UDP echo port (port number 7) on the remote machine, send a datagram, and receive the echoed response. The machine is considered unreachable if it can’t connect, if the reply datagram isn’t received, or if the reply differs from the original datagram. The ping method returns true if the machine was reachable, false otherwise.

You can also ping using other protocols by passing the protocol name to new. Valid protocols are tcp, udp, and icmp (all lowercase). A TCP ping attempts to connect to the echo port (TCP port 7) on the remote machine, and returns true if the connection could be established, false otherwise (unlike UDP ping, no data is sent to be echoed). An ICMP ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.