Perl Cookbook

Perl CookbookSearch this book
Previous: 18.6. Simulating Telnet from a ProgramChapter 18
Internet Services
Next: 18.8. Using Whois to Retrieve Information from the InterNIC
 

18.7. 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 ping uses the ICMP protocol, as does the ping (8) command. On Unix machines, you must be the superuser to use the ICMP protocol:

# use TCP if we're not root, ICMP if we are
$pong = Net::Ping->new( $> ? "tcp" : "icmp" );

(defined $pong)
    or die "Couldn't create Net::Ping object: $!\n";

if ($pong->ping("kingkong.com")) {
    print "The giant ape lives!\n";
} else {
    print "All hail mighty Gamera, friend of children!\n";
}

All these ping methods are prone to failure. Some sites filter the ICMP protocol at their router, so Net::Ping will say such machines are down even though you can connect using other protocols. Similarly, many machines disable the TCP and UDP echo services, causing TCP and UDP pings to fail. There is no way to know whether the ping failed because the service is disabled or filtered, or because the machine is actually down.

See Also

The documentation for the Net::Ping module from CPAN; your system's ping (8), tcp (4), udp (4), and icmp (4) manpages (if you have them); RFC 792 and 950


Previous: 18.6. Simulating Telnet from a ProgramPerl CookbookNext: 18.8. Using Whois to Retrieve Information from the InterNIC
18.6. Simulating Telnet from a ProgramBook Index18.8. Using Whois to Retrieve Information from the InterNIC