This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Refresh CPAN to 1.09
[perl5.git] / lib / Net / Ping.pm
CommitLineData
a0d0e21e
LW
1package Net::Ping;
2
3# Authors: karrer@bernina.ethz.ch (Andreas Karrer)
4# pmarquess@bfsec.bt.co.uk (Paul Marquess)
5
a79c1648 6require 5.002 ;
a0d0e21e
LW
7require Exporter;
8
a79c1648
PP
9use strict ;
10use vars qw(@ISA @EXPORT $VERSION $tcp_proto $echo_port) ;
11
a0d0e21e
LW
12@ISA = qw(Exporter);
13@EXPORT = qw(ping pingecho);
a79c1648 14$VERSION = 1.01;
a0d0e21e 15
8e07c86e 16use Socket 'PF_INET', 'AF_INET', 'SOCK_STREAM';
a79c1648 17use Carp ;
8e07c86e 18
a79c1648
PP
19$tcp_proto = (getprotobyname('tcp'))[2];
20$echo_port = (getservbyname('echo', 'tcp'))[2];
a0d0e21e
LW
21
22sub ping {
a79c1648 23 croak "ping not implemented yet. Use pingecho()";
a0d0e21e
LW
24}
25
26
27sub pingecho {
28
a79c1648
PP
29 croak "usage: pingecho host [timeout]"
30 unless @_ == 1 or @_ == 2 ;
a0d0e21e 31
8e07c86e
AD
32 my ($host, $timeout) = @_;
33 my ($saddr, $ip);
34 my ($ret) ;
a0d0e21e 35 local (*PINGSOCK);
a0d0e21e
LW
36
37 # check if $host is alive by connecting to its echo port, within $timeout
38 # (default 5) seconds. returns 1 if OK, 0 if no answer, 0 if host not found
39
40 $timeout = 5 unless $timeout;
41
42 if ($host =~ /^\s*((\d+\.){3}\d+)\s*$/)
43 { $ip = pack ('C4', split (/\./, $1)) }
44 else
45 { $ip = (gethostbyname($host))[4] }
46
47 return 0 unless $ip; # "no such host"
48
a79c1648 49 $saddr = pack('S n a4 x8', AF_INET, $echo_port, $ip);
a0d0e21e
LW
50 $SIG{'ALRM'} = sub { die } ;
51 alarm($timeout);
8e07c86e
AD
52
53 $ret = 0;
54 eval <<'EOM' ;
a79c1648 55 return unless socket(PINGSOCK, PF_INET, SOCK_STREAM, $tcp_proto) ;
8e07c86e
AD
56 return unless connect(PINGSOCK, $saddr) ;
57 $ret=1 ;
a0d0e21e 58EOM
a0d0e21e
LW
59 alarm(0);
60 close(PINGSOCK);
8e07c86e 61 $ret;
a0d0e21e
LW
62}
63
641;
8e07c86e
AD
65__END__
66
67=cut
68
69=head1 NAME
70
71Net::Ping, pingecho - check a host for upness
72
73=head1 SYNOPSIS
74
75 use Net::Ping;
76 print "'jimmy' is alive and kicking\n" if pingecho('jimmy', 10) ;
77
78=head1 DESCRIPTION
79
80This module contains routines to test for the reachability of remote hosts.
81Currently the only routine implemented is pingecho().
82
83pingecho() uses a TCP echo (I<not> an ICMP one) to determine if the
84remote host is reachable. This is usually adequate to tell that a remote
85host is available to rsh(1), ftp(1), or telnet(1) onto.
86
87=head2 Parameters
88
89=over 5
90
91=item hostname
92
93The remote host to check, specified either as a hostname or as an IP address.
94
95=item timeout
96
97The timeout in seconds. If not specified it will default to 5 seconds.
98
99=back
100
101=head1 WARNING
102
103pingecho() uses alarm to implement the timeout, so don't set another alarm
104while you are using it.
105
106