Net::Ping(3pm)

Net::Ping(3pm) ๐Ÿฆ‹

straight from the Perl Programmers Reference Guide: this is the manual page for Net::Ping, bestie, and it's literally about checking whether a remote host is reachable ๐Ÿ’…โœจ

NAME ๐Ÿ’–

Net::Ping โ€” check a remote host for reachability. periodt.

SYNOPSIS โœจ

okay so here's the copy-paste energy, exactly as the page gives it:

use Net::Ping;

my $p = Net::Ping->new();
print "$host is alive.\n" if $p->ping($host);
$p->close();

my $p = Net::Ping->new("icmp");
$p->bind($my_addr); # Specify source interface of pings
foreach my $host (@host_array)
{
    print "$host is ";
    print "NOT " unless $p->ping($host, 2);
    print "reachable.\n";
    sleep(1);
}
$p->close();

my $p = Net::Ping->new("icmpv6");
my $ip = "[fd00:dead:beef::4e]";
print "$ip is alive.\n" if $p->ping($ip);

my $p = Net::Ping->new("tcp", 2);
# Try connecting to the www port instead of the echo port
$p->port_number(scalar(getservbyname("http", "tcp")));
while ($stop_time > time())
{
    print "$host not reachable ", scalar(localtime()), "\n"
        unless $p->ping($host);
    sleep(300);
}
undef($p);

# Like tcp protocol, but with many hosts
my $p = Net::Ping->new("syn");
$p->port_number(getservbyname("http", "tcp"));
foreach my $host (@host_array) {
  $p->ping($host);
}
while (my ($host, $rtt, $ip) = $p->ack) {
  print "HOST: $host [$ip] ACKed in $rtt seconds.\n";
}

# High precision syntax (requires Time::HiRes)
my $p = Net::Ping->new();
$p->hires();
my ($ret, $duration, $ip) = $p->ping($host, 5.5);
printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n",
        1000 * $duration)
  if $ret;
$p->close();

# For backward compatibility
print "$host is alive.\n" if pingecho($host);

DESCRIPTION ๐Ÿ’ซ

This module contains methods to test the reachability of remote hosts on a network. A ping object is first created with optional parameters, a variable number of hosts may be pinged multiple times and then the connection is closed.

You may choose one of six different protocols to use for the ping. The tcp protocol is the default. Note that a live remote host may still fail to be pingable by one or more of these protocols. For example, www.microsoft.com is generally alive but not icmp pingable.

  • tcp โ€” with the tcp protocol the ping() method attempts to establish a connection to the remote host's echo port. If the connection is successfully established, the remote host is considered reachable. No data is actually echoed. This protocol does not require any special privileges but has higher overhead than the udp and icmp protocols.
  • udp โ€” specifying the udp protocol causes the ping() method to send a udp packet to the remote host's echo port. If the echoed packet is received from the remote host and the received packet contains the same data as the packet that was sent, the remote host is considered reachable. This protocol does not require any special privileges. It should be borne in mind that, for a udp ping, a host will be reported as unreachable if it is not running the appropriate echo service. For Unix-like systems see inetd(8) for more information.
  • icmp โ€” if the icmp protocol is specified, the ping() method sends an icmp echo message to the remote host, which is what the UNIX ping program does. If the echoed message is received from the remote host and the echoed information is correct, the remote host is considered reachable. Specifying the icmp protocol requires that the program be run as root or that the program be setuid to root.
  • external โ€” if the external protocol is specified, the ping() method attempts to use the Net::Ping::External module to ping the remote host. Net::Ping::External interfaces with your system's default ping utility to perform the ping, and generally produces relatively accurate results. If Net::Ping::External is not installed on your system, specifying the external protocol will result in an error.
  • syn โ€” if the syn protocol is specified, the ping method will only send a TCP SYN packet to the remote host then immediately return. If the syn packet was sent successfully, it will return a true value, otherwise it will return false. NOTE: Unlike the other protocols, the return value does NOT determine if the remote host is alive or not since the full TCP three-way handshake may not have completed yet. The remote host is only considered reachable if it receives a TCP ACK within the timeout specified. To begin waiting for the ACK packets, use the ack method as explained below. Use the syn protocol instead of the tcp protocol to determine reachability of multiple destinations simultaneously by sending parallel TCP SYN packets. It will not block while testing each remote host. This protocol does not require any special privileges.

Functions ๐ŸŽ€

๐ŸŒŸ Net::Ping->new(...) โ€” the constructor ๐ŸŒŸ

Net::Ping->new([proto, timeout, bytes, device, tos, ttl, family, host,
port, bind, gateway, retrans, pingstring, source_verify econnrefused
dontfrag IPV6_USE_MIN_MTU IPV6_RECVPATHMTU])

Create a new ping object. All of the parameters are optional and can be passed as hash ref. All options besides the first 7 must be passed as hash ref.

  • proto โ€” specifies the protocol to use when doing a ping. The current choices are tcp, udp, icmp, icmpv6, stream, syn, or external. The default is tcp.
  • timeout โ€” if a timeout in seconds is provided, it is used when a timeout is not given to the ping() method (below). The timeout must be greater than 0 and the default, if not specified, is 5 seconds.
  • bytes โ€” if the number of data bytes (bytes) is given, that many data bytes are included in the ping packet sent to the remote host. The number of data bytes is ignored if the protocol is tcp. The minimum (and default) number of data bytes is 1 if the protocol is udp and 0 otherwise. The maximum number of data bytes that can be specified is 65535, but staying below the MTU (1472 bytes for ICMP) is recommended. Many small devices cannot deal with fragmented ICMP packets.
  • device โ€” if device is given, this device is used to bind the source endpoint before sending the ping packet. I believe this only works with superuser privileges and with udp and icmp protocols at this time.
  • tos โ€” if tos is given, this ToS is configured into the socket.
  • ttl โ€” for icmp, ttl can be specified to set the TTL of the outgoing packet.
  • family โ€” valid family values for IPv4 are 4, v4, ip4, ipv4, and AF_INET (constant). Valid family values for IPv6 are 6, v6, ip6, ipv6, and AF_INET6 (constant). The host argument implicitly specifies the family if the family argument is not given.
  • host โ€” the host argument implicitly specifies the family if the family argument is not given.
  • port โ€” the port argument is only valid for a udp, tcp or stream ping, and will not do what you think it does. ping returns true when we get a Connection refused! The default is the echo port.
  • bind โ€” the bind argument specifies the local_addr to bind to. By specifying a bind argument you don't need the bind method.
  • gateway โ€” the gateway argument is only valid for IPv6, and requires a IPv6 address.
  • retrans โ€” the retrans argument the exponential backoff rate, default 1.2. It matches the $def_factor global.
  • dontfrag โ€” the dontfrag argument sets the IP_DONTFRAG bit, but note that IP_DONTFRAG is not yet defined by Socket, and not available on many systems. Then it is ignored. On linux it also sets IP_MTU_DISCOVER to IP_PMTUDISC_DO but need we don't chunk oversized packets. You need to set $data_size manually.

๐Ÿ’ฅ $p->ping($host [, $timeout [, $family]]); ๐Ÿ’ฅ

Ping the remote host and wait for a response. $host can be either the hostname or the IP number of the remote host. The optional timeout must be greater than 0 seconds and defaults to whatever was specified when the ping object was created. Returns a success flag. If the hostname cannot be found or there is a problem with the IP number, the success flag returned will be undef. Otherwise, the success flag will be 1 if the host is reachable and 0 if it is not. For most practical purposes, undef and 0 and can be treated as the same case. In array context, the elapsed time as well as the string form of the ip the host resolved to are also returned. The elapsed time value will be a float, as returned by the Time::HiRes::time() function, if hires() has been previously called, otherwise it is returned as an integer.

๐Ÿซถ $p->source_verify( { 0 | 1 } ); ๐Ÿซถ

Allows source endpoint verification to be enabled or disabled. This is useful for those remote destinations with multiples interfaces where the response may not originate from the same endpoint that the original destination endpoint was sent to. This only affects udp and icmp protocol pings.

This is enabled by default.

๐Ÿ‘‘ $p->service_check( { 0 | 1 } ); ๐Ÿ‘‘

Set whether or not the connect behavior should enforce remote service availability as well as reachability. Normally, if the remote server reported ECONNREFUSED, it must have been reachable because of the status packet that it reported. With this option enabled, the full three-way tcp handshake must have been established successfully before it will claim it is reachable. NOTE: It still does nothing more than connect and disconnect. It does not speak any protocol (i.e., HTTP or FTP) to ensure the remote server is sane in any way. The remote server CPU could be grinding to a halt and unresponsive to any clients connecting, but if the kernel throws the ACK packet, it is considered alive anyway. To really determine if the server is responding well would be application specific and is beyond the scope of Net::Ping. For udp protocol, enabling this option demands that the remote server replies with the same udp data that it was sent as defined by the udp echo service.

This affects the udp, tcp, and syn protocols.

This is disabled by default.

๐Ÿ’€ $p->tcp_service_check( { 0 | 1 } ); ๐Ÿ’€

Deprecated method, but does the same as service_check() method.

๐ŸŽ€ $p->hires( { 0 | 1 } ); ๐ŸŽ€

With 1 causes this module to use Time::HiRes module, allowing milliseconds to be returned by subsequent calls to ping().

โญ $p->time โญ

The current time, hires or not.

๐Ÿงš $p->socket_blocking_mode( $fh, $mode ); ๐Ÿงš

Sets or clears the O_NONBLOCK flag on a file handle.

๐ŸŒˆ $p->IPV6_USE_MIN_MTU ๐ŸŒˆ

With argument sets the option. Without returns the option value.

๐ŸŒˆ $p->IPV6_RECVPATHMTU ๐ŸŒˆ

Notify an according IPv6 MTU.

With argument sets the option. Without returns the option value.

๐ŸŒˆ $p->IPV6_HOPLIMIT ๐ŸŒˆ

With argument sets the option. Without returns the option value.

  • $p->IPV6_REACHCONF NYI โ€” okay so this one would set the ipv6 reachability, but plot twist: IPV6_REACHCONF was removed in RFC3542 ๐Ÿ’€. ping6 -R still supports it tho. Using it needs root/admin permissions. Call it with an argument and it sets the option; call it with no argument and it hands you back the option value. And the vibe check? Not yet implemented. ๐Ÿ™ˆ
  • $p->bind($local_addr); โ€” sets the source address your pings get sent from โœจ. This has to be the address of one of the interfaces on the local host, no exceptions. $local_addr can be a hostname or a text IP address like "192.168.1.1".

Now the rules, and bestie these rules are serious ๐Ÿ‘‘: if the protocol is "tcp", you can call this method any number of times, and each call to the ping() method (below) will use the most recent $local_addr. But if the protocol is "icmp" or "udp", then bind() must be called at most once per object, and (if it gets called at all) it must be called before the first call to ping() for that object. No takebacks, no do-overs. ๐Ÿ˜ค

Also you can just skip bind() entirely by specifying the "bind" option to new() โ€” iconic shortcut behavior ๐Ÿ’….

  • $p->message_type([$ping_type]); โ€” while you're on the "icmp" protocol, this call lets you swap the message type to 'echo' or 'timestamp' (IPv4 only, see RFC 792, iykyk ๐Ÿงš).

No argument? It returns the icmp protocol message type currently in use. Default is 'echo'. Simple, clean, slay โœจ.

  • $p->open($host); โ€” for the "stream" protocol, this pre-opens the tcp socket ๐Ÿซถ. You only need it if you want to hand it a different timeout when creating the connection, or if you want to yeet the overhead of establishing the connection out of your first ping. If you don't call open(), the connection just opens itself automatically the first time ping() runs โ€” main character energy, it handles itself ๐Ÿ’…. And if you're on any protocol other than stream? This call simply does nothing. Literally nothing. ๐Ÿ˜Œ

The $host argument can be omitted if you specified the "host" option to new().

  • $p->ack( [ $host ] ); โ€” "syn" protocol bestie, this is your reachability check ๐ŸŽ€. Call it up to as many times as you called ping(). Each call returns the host (as passed to ping()) that came back with the TCP ACK.

Heads up tho โ€” the order the hosts come back in may not necessarily be the same order you SYN-queued them with ping() ๐Ÿ˜ญ. Rude but true. If the timeout hits before the TCP ACK arrives, or if the remote host isn't listening on the port you attempted, then the TCP connection won't get established and ack() returns undef. ๐Ÿ’€

In list context you get the host, the ack time, the dotted ip string, and the port number โ€” instead of just the host. Upgrade! โœจ If you pass the optional $host argument, the return value will pertain to that host only. Any protocol other than "syn"? This call simply does nothing.

When "new" had a host option, that host will be used. And with no $host argument, all hosts get scanned ๐Ÿ‘‘

  • $p->nack( $failed_ack_host ); โ€” the reason that host $failed_ack_host didn't receive a valid ACK ๐Ÿซถ. Super useful for figuring out why when ack($fail_ack_host) returns a false value. It's giving detective energy ๐Ÿ”.
  • $p->ack_unfork($host) โ€” the variant that gets called by ack when you're on the "syn" protocol and $syn_forking is enabled. That's it, that's the whole thing ๐Ÿฆ‹.
  • $p->ping_icmp([$host, $timeout, $family]) โ€” the ping method used with the icmp protocol. ๐Ÿ’œ
  • $p->ping_icmpv6([$host, $timeout, $family]) โ€” the ping method used with the icmpv6 protocol. ๐Ÿ’œ
  • $p->ping_stream([$host, $timeout, $family]) โ€” the ping method used with the stream protocol.

It performs a stream ping ๐ŸŒธ. If the tcp connection isn't already open, it opens it. Then it sends some data and waits for a reply. And it leaves the stream open on exit โ€” no cleanup, we die like legends ๐Ÿ’….

  • $p->ping_syn([$host, $ip, $start_time, $stop_time]) โ€” the ping method used with the syn protocol. Sends a TCP SYN packet to the host specified. That's the whole bit, no cap ๐Ÿ”ฅ.
  • $p->ping_syn_fork([$host, $timeout, $family]) โ€” the ping method used with the forking syn protocol. ๐Ÿงš
  • $p->ping_tcp([$host, $timeout, $family]) โ€” the ping method used with the tcp protocol. ๐ŸŽ€
  • $p->ping_udp([$host, $timeout, $family]) โ€” the ping method used with the udp protocol.

Performs a udp echo ping โœจ. Construct a message of at least the one-byte sequence number and any additional data bytes. Send the message out and wait for a message to come back. If we get a message, make sure all of its parts match. If they do, we are done, we ate, periodt ๐Ÿ“. Otherwise go back and wait for the message until we run out of time. Return the result of our efforts. ๐Ÿ˜ค

  • $p->ping_external([$host, $timeout, $family]) โ€” the ping method used with the external protocol. Uses Net::Ping::External to do an external ping. Outsourced! ๐Ÿซถ
  • $p->tcp_connect([$ip, $timeout]) โ€” initiates a TCP connection, for a tcp ping. Let's gooo ๐Ÿ”ฅ
  • $p->tcp_echo([$ip, $timeout, $pingstring]) โ€” performs a TCP echo. It writes the given string to the socket and then reads it back. Returns 1 on success, 0 on failure. Binary queen ๐Ÿ’…
  • $p->close(); โ€” closes the network connection for this ping object ๐ŸŽ€. The network connection also gets closed by undef $p. And it's automatically closed if the ping object goes out of scope (e.g. $p is local to a subroutine and you leave the subroutine). It cleans up after itself, we love a self-sufficient icon โœจ.
  • $p->port_number([$port_number]) โ€” call it with a port number and the port number used to ping gets set to $port_number instead of using the echo port ๐ŸŒธ. It also has the effect of calling $p->service_check(1), which causes a ping to return a successful response only if that specific port is accessible. Picky but valid ๐Ÿ˜Œ. This function returns the value of the port that ping will connect to.
  • $p->mselect โ€” a select() wrapper that compensates for platform peculiarities. Holding it down for every weird OS out there ๐Ÿซถ
  • $p->ntop โ€” platform abstraction over inet_ntop(). Same energy, different platform ๐Ÿ’œ.
  • $p->checksum($msg) โ€” do a checksum on the message. Basically sum all of the short words and fold the high order bits into the low order bits. Math girlie behavior ๐Ÿงฎโœจ.
  • $p->icmp_result โ€” returns a list of addr, type, subcode. Three for the price of one ๐Ÿ‘‘
  • pingecho($host [, $timeout]); โ€” for backward compatibility with the previous version of Net::Ping, a pingecho() subroutine is available with the same functionality as before ๐ŸŽ€. pingecho() uses the tcp protocol. The return values and parameters are the same as described for the ping method.
Real talk: this subroutine is obsolete and may be removed in a future version of Net::Ping. Use it, but don't get attached ๐Ÿ˜ญ
  • wakeonlan($mac, [$host, [$port]]) โ€” emit the popular wake-on-lan magic udp packet to wake up a local device ๐ŸŒˆ. See also Net::Wake, but this one has the mac address as 1st arg. $host should be the local gateway. Without it, it'll broadcast ๐Ÿ“ก.

Default host: '255.255.255.255' Default port: 9

perl -MNet::Ping=wakeonlan -e'wakeonlan "e0:69:95:35:68:d2"'

Rise and shine bestie, your device is awake โ˜€๏ธ๐Ÿ’…


๐Ÿ“ NOTES ๐Ÿ“

There will be less network overhead (and some efficiency in your program) if you specify either the udp or the icmp protocol โœจ. The tcp protocol will generate 2.5 times or more traffic for each ping than either udp or icmp ๐Ÿ’€. So if many hosts are pinged frequently, you may wish to implement a small wait (e.g. 25ms or more) between each ping to avoid flooding your network with packets. Be polite to your network, it's literally doing its best ๐Ÿซถ

The icmp and icmpv6 protocols require that the program be run as root or that it be setuid to root ๐Ÿ‘‘. The other protocols do not require special privileges, but not all network devices implement tcp or udp echo. Trade-offs, bestie ๐Ÿ˜ญ

Local hosts should normally respond to pings within milliseconds. However, on a very congested network it may take up to 3 seconds or longer to receive an echo packet from the remote host ๐Ÿ˜ฎโ€๐Ÿ’จ. If the timeout is set too low under these conditions, it will appear that the remote host is not reachable (which is almost the truth). Almost! The audacity ๐Ÿ˜ค

Reachability doesn't necessarily mean that the remote host is actually functioning beyond its ability to echo packets ๐ŸŒธ. tcp is slightly better at indicating the health of a system than icmp because it uses more of the networking stack to respond. More stack, more answers ๐Ÿ’…

Because of a lack of anything better, this module uses its own routines to pack and unpack ICMP packets ๐Ÿ’€. It would be better for a separate module to be written which understands all of the different kinds of ICMP packets. Manifesting that module for whoever needs it ๐Ÿ™โœจ


๐Ÿ› ๏ธ INSTALL ๐Ÿ› ๏ธ

The latest source tree is available via git:

git clone https://github.com/rurban/Net-Ping.git
cd Net-Ping

The tarball can be created as follows:

perl Makefile.PL ; make ; make dist

The latest Net::Ping releases are included in cperl and perl5 ๐ŸŽ€. Convenient or what.


๐Ÿ› BUGS ๐Ÿ›

For a list of known issues, visit:

<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Ping> and <https://github.com/rurban/Net-Ping/issues>

To report a new bug, visit:

<https://github.com/rurban/Net-Ping/issues>

Go off, report that bug, you're doing the community a service ๐Ÿซถ๐Ÿ’–


๐Ÿ‘‘ AUTHORS ๐Ÿ‘‘

  • Current maintainers:
    • perl11 (for cperl, with IPv6 support and more)
    • p5p (for perl5)
  • Previous maintainers:
    • bbb@cpan.org (Rob Brown)
    • Steve Peters
  • External protocol:
    • colinm@cpan.org (Colin McMillen)
  • Stream protocol:
    • bronson@trestle.com (Scott Bronson)
  • Wake-on-lan:
    • 1999-2003 Clinton Wong
  • Original pingecho():
    • karrer@bernina.ethz.ch (Andreas Karrer)
    • pmarquess@bfsec.bt.co.uk (Paul Marquess)
  • Original Net::Ping author:
    • mose@ns.ccsn.edu (Russell Mosemann)

Every single one of them a legend, fr fr ๐ŸŒŸ


Copyright (c) 2017-2020, Reini Urban. All rights reserved.

Copyright (c) 2016, cPanel Inc. All rights reserved.

Copyright (c) 2012, Steve Peters. All rights reserved.

Copyright (c) 2002-2003, Rob Brown. All rights reserved.

Copyright (c) 2001, Colin McMillen. All rights reserved.

This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. ๐Ÿ’œ


And that's the whole page bestie ๐ŸŽ€๐Ÿ’–โœจ โ€” this was Net::Ping(3pm) from perl v5.42.3, dated 2026-11-03. Go ping something responsibly, drink some water, and remember: icmp needs root ๐Ÿ‘‘๐Ÿ’…

๐Ÿ“ฆ where this page comes from