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 thetcpprotocol theping()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 theudpandicmpprotocols.udpโ specifying theudpprotocol causes theping()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 seeinetd(8)for more information.icmpโ if theicmpprotocol is specified, theping()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 theicmpprotocol requires that the program be run as root or that the program be setuid to root.externalโ if theexternalprotocol is specified, theping()method attempts to use theNet::Ping::Externalmodule to ping the remote host.Net::Ping::Externalinterfaces with your system's defaultpingutility to perform the ping, and generally produces relatively accurate results. IfNet::Ping::Externalis not installed on your system, specifying theexternalprotocol will result in an error.synโ if thesynprotocol is specified, thepingmethod 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 theackmethod as explained below. Use thesynprotocol instead of thetcpprotocol 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 aretcp,udp,icmp,icmpv6,stream,syn, orexternal. The default istcp.timeoutโ if atimeoutin seconds is provided, it is used when a timeout is not given to theping()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 istcp. The minimum (and default) number of data bytes is 1 if the protocol isudpand 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โ ifdeviceis 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โ iftosis given, this ToS is configured into the socket.ttlโ for icmp,ttlcan be specified to set the TTL of the outgoing packet.familyโ validfamilyvalues for IPv4 are4,v4,ip4,ipv4, andAF_INET(constant). Validfamilyvalues for IPv6 are6,v6,ip6,ipv6, andAF_INET6(constant). Thehostargument implicitly specifies the family if the family argument is not given.hostโ thehostargument implicitly specifies the family if the family argument is not given.portโ theportargument 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 aConnection refused! The default is the echo port.bindโ thebindargument specifies the local_addr to bind to. By specifying a bind argument you don't need the bind method.gatewayโ thegatewayargument is only valid for IPv6, and requires a IPv6 address.retransโ theretransargument the exponential backoff rate, default 1.2. It matches the$def_factorglobal.dontfragโ thedontfragargument sets theIP_DONTFRAGbit, but note thatIP_DONTFRAGis not yet defined by Socket, and not available on many systems. Then it is ignored. On linux it also setsIP_MTU_DISCOVERtoIP_PMTUDISC_DObut need we don't chunk oversized packets. You need to set$data_sizemanually.
๐ฅ $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_REACHCONFNYI โ okay so this one would set the ipv6 reachability, but plot twist:IPV6_REACHCONFwas removed in RFC3542 ๐.ping6 -Rstill 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_addrcan 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 callopen(), the connection just opens itself automatically the first timeping()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 calledping(). Each call returns the host (as passed toping()) 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 thathost $failed_ack_hostdidn't receive a valid ACK ๐ซถ. Super useful for figuring out why whenack($fail_ack_host)returns a false value. It's giving detective energy ๐.$p->ack_unfork($host)โ the variant that gets called byackwhen you're on the"syn"protocol and$syn_forkingis enabled. That's it, that's the whole thing ๐ฆ.$p->ping_icmp([$host, $timeout, $family])โ thepingmethod used with the icmp protocol. ๐$p->ping_icmpv6([$host, $timeout, $family])โ thepingmethod used with the icmpv6 protocol. ๐$p->ping_stream([$host, $timeout, $family])โ thepingmethod 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])โ thepingmethod 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])โ thepingmethod used with the forking syn protocol. ๐ง$p->ping_tcp([$host, $timeout, $family])โ thepingmethod used with the tcp protocol. ๐$p->ping_udp([$host, $timeout, $family])โ thepingmethod 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])โ thepingmethod 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. Returns1on success,0on failure. Binary queen ๐$p->close();โ closes the network connection for this ping object ๐. The network connection also gets closed byundef $p. And it's automatically closed if the ping object goes out of scope (e.g.$pis 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_numberinstead 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 thatpingwill connect to.$p->mselectโ aselect()wrapper that compensates for platform peculiarities. Holding it down for every weird OS out there ๐ซถ$p->ntopโ platform abstraction overinet_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, apingecho()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 thepingmethod.
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.$hostshould 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-2003Clinton 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 ยฉ๏ธ
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
- alpine 3.24: perl-doc 5.42.3-r0 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms