1. Perl
  2. Module
  3. here

Net::Ping - Check the existence of the remote host

You can check the existence of the remote host by using the Net::Ping module.

# Loading modules and creating objects
use Net::Ping;
my $p = Net::Ping->new;

Use the ping method to check the existence of the remote host. You can use the host name (domain name) and IP address as arguments.

# Check the existence of the remote host
my $alive = $p->ping('localhost');

One thing to note is that the Net::Ping ping method is not an alternative to the ping command. Ping command Although it uses a protocol called ICMP, Net::Ping uses the TCP protocol by default to check for survival on the echo port (port number 7). For example, even if you can connect to a remote host via HTTP (port 80), if you close the echo port for security reasons, you will get a judgment that it is not alive.

To check the existence using ICMP, specify icmp in the constructor. However, you need root privileges to do this (* 1).

# Survival check using ICMP
my $p = Net::Ping->new('icmp');
my $alive = $p->ping('somehost');

If you want to check the existence by HTTP, use the port_number method and specify 80 as the port number. (v5.10.0 or later)

# Survival check using HTTP
$p->port_number(80);
my $alive = $p->ping('www.google.co.jp');

You can specify the timeout value (seconds) in the second argument of the ping method.

# Specify timeout value
my $alive = $p->ping('www.google.co.jp', 2);

Documents

Note

* 1 It is a little inconvenient that you cannot confirm the existence without root authority. CPAN has a module called Net::Ping::External, which is the Perl interface for the ping command. If you use this, you can check the existence by using ICMP without root authority.

Related Informatrion