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