18.7. Pinging a MachineProblem
You want to test whether a machine is alive. Network and system monitoring software often use the SolutionUse 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; DiscussionTesting 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
You can also ping using other protocols by passing the protocol name to # 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 AlsoThe 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 Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|