Commit | Line | Data |
a0d0e21e |
1 | package Net::Ping; |
2 | |
564e2e78 |
3 | # $Id: Ping.pm,v 1.34 2002/05/06 17:37:54 rob Exp $ |
b124990b |
4 | |
5 | require 5.002; |
a0d0e21e |
6 | require Exporter; |
7 | |
a3b93737 |
8 | use strict; |
b124990b |
9 | use vars qw(@ISA @EXPORT $VERSION |
e82f584b |
10 | $def_timeout $def_proto $max_datasize $pingstring $hires); |
a3b93737 |
11 | use FileHandle; |
12 | use Socket qw( SOCK_DGRAM SOCK_STREAM SOCK_RAW PF_INET |
e82f584b |
13 | inet_aton inet_ntoa sockaddr_in ); |
a3b93737 |
14 | use Carp; |
ef73e1db |
15 | use POSIX qw(ECONNREFUSED); |
a79c1648 |
16 | |
a0d0e21e |
17 | @ISA = qw(Exporter); |
a3b93737 |
18 | @EXPORT = qw(pingecho); |
564e2e78 |
19 | $VERSION = "2.18"; |
a0d0e21e |
20 | |
a3b93737 |
21 | # Constants |
a0d0e21e |
22 | |
a3b93737 |
23 | $def_timeout = 5; # Default timeout to wait for a reply |
a5a165b1 |
24 | $def_proto = "tcp"; # Default protocol to use for pinging |
a3b93737 |
25 | $max_datasize = 1024; # Maximum data bytes in a packet |
b124990b |
26 | # The data we exchange with the server for the stream protocol |
27 | $pingstring = "pingschwingping!\n"; |
a0d0e21e |
28 | |
ef73e1db |
29 | if ($^O =~ /Win32/i) { |
30 | # Hack to avoid this Win32 spewage: |
31 | # Your vendor has not defined POSIX macro ECONNREFUSED |
32 | *ECONNREFUSED = sub {10061;}; # "Unknown Error" Special Win32 Response? |
33 | }; |
34 | |
a3b93737 |
35 | # Description: The pingecho() subroutine is provided for backward |
36 | # compatibility with the original Net::Ping. It accepts a host |
37 | # name/IP and an optional timeout in seconds. Create a tcp ping |
38 | # object and try pinging the host. The result of the ping is returned. |
a0d0e21e |
39 | |
a3b93737 |
40 | sub pingecho |
41 | { |
e82f584b |
42 | my ($host, # Name or IP number of host to ping |
43 | $timeout # Optional timeout in seconds |
44 | ) = @_; |
45 | my ($p); # A ping object |
a0d0e21e |
46 | |
e82f584b |
47 | $p = Net::Ping->new("tcp", $timeout); |
48 | $p->ping($host); # Going out of scope closes the connection |
a3b93737 |
49 | } |
a0d0e21e |
50 | |
a3b93737 |
51 | # Description: The new() method creates a new ping object. Optional |
52 | # parameters may be specified for the protocol to use, the timeout in |
53 | # seconds and the size in bytes of additional data which should be |
54 | # included in the packet. |
55 | # After the optional parameters are checked, the data is constructed |
56 | # and a socket is opened if appropriate. The object is returned. |
57 | |
58 | sub new |
59 | { |
e82f584b |
60 | my ($this, |
61 | $proto, # Optional protocol to use for pinging |
62 | $timeout, # Optional timeout in seconds |
63 | $data_size # Optional additional bytes of data |
64 | ) = @_; |
65 | my $class = ref($this) || $this; |
66 | my $self = {}; |
67 | my ($cnt, # Count through data bytes |
68 | $min_datasize # Minimum data bytes required |
69 | ); |
70 | |
71 | bless($self, $class); |
72 | |
73 | $proto = $def_proto unless $proto; # Determine the protocol |
74 | croak('Protocol for ping must be "icmp", "udp", "tcp", "stream", or "external"') |
75 | unless $proto =~ m/^(icmp|udp|tcp|stream|external)$/; |
76 | $self->{"proto"} = $proto; |
77 | |
78 | $timeout = $def_timeout unless $timeout; # Determine the timeout |
79 | croak("Default timeout for ping must be greater than 0 seconds") |
80 | if $timeout <= 0; |
81 | $self->{"timeout"} = $timeout; |
82 | |
83 | $min_datasize = ($proto eq "udp") ? 1 : 0; # Determine data size |
84 | $data_size = $min_datasize unless defined($data_size) && $proto ne "tcp"; |
85 | croak("Data for ping must be from $min_datasize to $max_datasize bytes") |
86 | if ($data_size < $min_datasize) || ($data_size > $max_datasize); |
87 | $data_size-- if $self->{"proto"} eq "udp"; # We provide the first byte |
88 | $self->{"data_size"} = $data_size; |
89 | |
90 | $self->{"data"} = ""; # Construct data bytes |
91 | for ($cnt = 0; $cnt < $self->{"data_size"}; $cnt++) |
92 | { |
93 | $self->{"data"} .= chr($cnt % 256); |
94 | } |
95 | |
96 | $self->{"local_addr"} = undef; # Don't bind by default |
97 | |
98 | $self->{"seq"} = 0; # For counting packets |
99 | if ($self->{"proto"} eq "udp") # Open a socket |
100 | { |
101 | $self->{"proto_num"} = (getprotobyname('udp'))[2] || |
102 | croak("Can't udp protocol by name"); |
103 | $self->{"port_num"} = (getservbyname('echo', 'udp'))[2] || |
104 | croak("Can't get udp echo port by name"); |
105 | $self->{"fh"} = FileHandle->new(); |
106 | socket($self->{"fh"}, PF_INET, SOCK_DGRAM, |
107 | $self->{"proto_num"}) || |
108 | croak("udp socket error - $!"); |
109 | } |
110 | elsif ($self->{"proto"} eq "icmp") |
111 | { |
112 | croak("icmp ping requires root privilege") if ($> and $^O ne 'VMS'); |
113 | $self->{"proto_num"} = (getprotobyname('icmp'))[2] || |
114 | croak("Can't get icmp protocol by name"); |
115 | $self->{"pid"} = $$ & 0xffff; # Save lower 16 bits of pid |
116 | $self->{"fh"} = FileHandle->new(); |
117 | socket($self->{"fh"}, PF_INET, SOCK_RAW, $self->{"proto_num"}) || |
118 | croak("icmp socket error - $!"); |
119 | } |
120 | elsif ($self->{"proto"} eq "tcp" || $self->{"proto"} eq "stream") |
121 | { |
122 | $self->{"proto_num"} = (getprotobyname('tcp'))[2] || |
123 | croak("Can't get tcp protocol by name"); |
124 | $self->{"port_num"} = (getservbyname('echo', 'tcp'))[2] || |
125 | croak("Can't get tcp echo port by name"); |
126 | $self->{"fh"} = FileHandle->new(); |
127 | } |
128 | |
129 | return($self); |
a3b93737 |
130 | } |
a0d0e21e |
131 | |
49afa5f6 |
132 | # Description: Set the local IP address from which pings will be sent. |
133 | # For ICMP and UDP pings, this calls bind() on the already-opened socket; |
134 | # for TCP pings, just saves the address to be used when the socket is |
135 | # opened. Returns non-zero if successful; croaks on error. |
136 | sub bind |
137 | { |
e82f584b |
138 | my ($self, |
139 | $local_addr # Name or IP number of local interface |
140 | ) = @_; |
141 | my ($ip # Packed IP number of $local_addr |
142 | ); |
143 | |
144 | croak("Usage: \$p->bind(\$local_addr)") unless @_ == 2; |
145 | croak("already bound") if defined($self->{"local_addr"}) && |
146 | ($self->{"proto"} eq "udp" || $self->{"proto"} eq "icmp"); |
147 | |
148 | $ip = inet_aton($local_addr); |
149 | croak("nonexistent local address $local_addr") unless defined($ip); |
150 | $self->{"local_addr"} = $ip; # Only used if proto is tcp |
151 | |
152 | if ($self->{"proto"} eq "udp" || $self->{"proto"} eq "icmp") |
153 | { |
154 | CORE::bind($self->{"fh"}, sockaddr_in(0, $ip)) || |
155 | croak("$self->{'proto'} bind error - $!"); |
156 | } |
157 | elsif ($self->{"proto"} ne "tcp") |
158 | { |
159 | croak("Unknown protocol \"$self->{proto}\" in bind()"); |
160 | } |
161 | |
162 | return 1; |
163 | } |
49afa5f6 |
164 | |
49afa5f6 |
165 | |
e82f584b |
166 | # Description: allows the module to use milliseconds as returned by |
167 | # the Time::HiRes module |
49afa5f6 |
168 | |
e82f584b |
169 | $hires = 0; |
170 | sub hires |
171 | { |
172 | my $self = shift; |
173 | $hires = 1 unless defined |
174 | ($hires = ((defined $self) && (ref $self)) ? shift() : $self); |
175 | require Time::HiRes if $hires; |
49afa5f6 |
176 | } |
177 | |
e82f584b |
178 | sub time |
179 | { |
180 | return $hires ? Time::HiRes::time() : CORE::time(); |
181 | } |
49afa5f6 |
182 | |
a3b93737 |
183 | # Description: Ping a host name or IP number with an optional timeout. |
184 | # First lookup the host, and return undef if it is not found. Otherwise |
b124990b |
185 | # perform the specific ping method based on the protocol. Return the |
a3b93737 |
186 | # result of the ping. |
187 | |
188 | sub ping |
189 | { |
e82f584b |
190 | my ($self, |
191 | $host, # Name or IP number of host to ping |
192 | $timeout, # Seconds after which ping times out |
193 | ) = @_; |
194 | my ($ip, # Packed IP number of $host |
195 | $ret, # The return value |
196 | $ping_time, # When ping began |
197 | ); |
198 | |
199 | croak("Usage: \$p->ping(\$host [, \$timeout])") unless @_ == 2 || @_ == 3; |
200 | $timeout = $self->{"timeout"} unless $timeout; |
201 | croak("Timeout must be greater than 0 seconds") if $timeout <= 0; |
202 | |
203 | $ip = inet_aton($host); |
204 | return(undef) unless defined($ip); # Does host exist? |
205 | |
206 | # Dispatch to the appropriate routine. |
207 | $ping_time = &time(); |
208 | if ($self->{"proto"} eq "external") { |
209 | $ret = $self->ping_external($ip, $timeout); |
210 | } |
211 | elsif ($self->{"proto"} eq "udp") { |
212 | $ret = $self->ping_udp($ip, $timeout); |
213 | } |
214 | elsif ($self->{"proto"} eq "icmp") { |
215 | $ret = $self->ping_icmp($ip, $timeout); |
216 | } |
217 | elsif ($self->{"proto"} eq "tcp") { |
218 | $ret = $self->ping_tcp($ip, $timeout); |
219 | } |
220 | elsif ($self->{"proto"} eq "stream") { |
221 | $ret = $self->ping_stream($ip, $timeout); |
222 | } else { |
787ecdfa |
223 | croak("Unknown protocol \"$self->{proto}\" in ping()"); |
e82f584b |
224 | } |
225 | |
226 | return wantarray ? ($ret, &time() - $ping_time, inet_ntoa($ip)) : $ret; |
787ecdfa |
227 | } |
228 | |
229 | # Uses Net::Ping::External to do an external ping. |
230 | sub ping_external { |
231 | my ($self, |
232 | $ip, # Packed IP number of the host |
233 | $timeout # Seconds after which ping times out |
234 | ) = @_; |
235 | |
b124990b |
236 | eval { require Net::Ping::External; } |
237 | or croak('Protocol "external" not supported on your system: Net::Ping::External not found'); |
787ecdfa |
238 | return Net::Ping::External::ping(ip => $ip, timeout => $timeout); |
a3b93737 |
239 | } |
a0d0e21e |
240 | |
49afa5f6 |
241 | use constant ICMP_ECHOREPLY => 0; # ICMP packet types |
242 | use constant ICMP_ECHO => 8; |
243 | use constant ICMP_STRUCT => "C2 S3 A"; # Structure of a minimal ICMP packet |
244 | use constant SUBCODE => 0; # No ICMP subcode for ECHO and ECHOREPLY |
245 | use constant ICMP_FLAGS => 0; # No special flags for send or recv |
246 | use constant ICMP_PORT => 0; # No port with ICMP |
247 | |
a3b93737 |
248 | sub ping_icmp |
249 | { |
e82f584b |
250 | my ($self, |
251 | $ip, # Packed IP number of the host |
252 | $timeout # Seconds after which ping times out |
253 | ) = @_; |
254 | |
255 | my ($saddr, # sockaddr_in with port and ip |
256 | $checksum, # Checksum of ICMP packet |
257 | $msg, # ICMP packet to send |
258 | $len_msg, # Length of $msg |
259 | $rbits, # Read bits, filehandles for reading |
260 | $nfound, # Number of ready filehandles found |
261 | $finish_time, # Time ping should be finished |
262 | $done, # set to 1 when we are done |
263 | $ret, # Return value |
264 | $recv_msg, # Received message including IP header |
265 | $from_saddr, # sockaddr_in of sender |
266 | $from_port, # Port packet was sent from |
267 | $from_ip, # Packed IP of sender |
268 | $from_type, # ICMP type |
269 | $from_subcode, # ICMP subcode |
270 | $from_chk, # ICMP packet checksum |
271 | $from_pid, # ICMP packet id |
272 | $from_seq, # ICMP packet sequence |
273 | $from_msg # ICMP message |
274 | ); |
275 | |
276 | $self->{"seq"} = ($self->{"seq"} + 1) % 65536; # Increment sequence |
277 | $checksum = 0; # No checksum for starters |
278 | $msg = pack(ICMP_STRUCT . $self->{"data_size"}, ICMP_ECHO, SUBCODE, |
279 | $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"}); |
280 | $checksum = Net::Ping->checksum($msg); |
281 | $msg = pack(ICMP_STRUCT . $self->{"data_size"}, ICMP_ECHO, SUBCODE, |
282 | $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"}); |
283 | $len_msg = length($msg); |
284 | $saddr = sockaddr_in(ICMP_PORT, $ip); |
285 | send($self->{"fh"}, $msg, ICMP_FLAGS, $saddr); # Send the message |
286 | |
287 | $rbits = ""; |
288 | vec($rbits, $self->{"fh"}->fileno(), 1) = 1; |
289 | $ret = 0; |
290 | $done = 0; |
291 | $finish_time = &time() + $timeout; # Must be done by this time |
292 | while (!$done && $timeout > 0) # Keep trying if we have time |
293 | { |
294 | $nfound = select($rbits, undef, undef, $timeout); # Wait for packet |
295 | $timeout = $finish_time - &time(); # Get remaining time |
296 | if (!defined($nfound)) # Hmm, a strange error |
a3b93737 |
297 | { |
e82f584b |
298 | $ret = undef; |
299 | $done = 1; |
300 | } |
301 | elsif ($nfound) # Got a packet from somewhere |
302 | { |
303 | $recv_msg = ""; |
304 | $from_saddr = recv($self->{"fh"}, $recv_msg, 1500, ICMP_FLAGS); |
305 | ($from_port, $from_ip) = sockaddr_in($from_saddr); |
306 | ($from_type, $from_subcode, $from_chk, |
307 | $from_pid, $from_seq, $from_msg) = |
308 | unpack(ICMP_STRUCT . $self->{"data_size"}, |
309 | substr($recv_msg, length($recv_msg) - $len_msg, |
310 | $len_msg)); |
311 | if (($from_type == ICMP_ECHOREPLY) && |
312 | ($from_ip eq $ip) && |
313 | ($from_pid == $self->{"pid"}) && # Does the packet check out? |
314 | ($from_seq == $self->{"seq"})) |
315 | { |
316 | $ret = 1; # It's a winner |
317 | $done = 1; |
318 | } |
a3b93737 |
319 | } |
e82f584b |
320 | else # Oops, timed out |
321 | { |
322 | $done = 1; |
323 | } |
324 | } |
325 | return $ret; |
a3b93737 |
326 | } |
327 | |
328 | # Description: Do a checksum on the message. Basically sum all of |
329 | # the short words and fold the high order bits into the low order bits. |
330 | |
331 | sub checksum |
332 | { |
e82f584b |
333 | my ($class, |
334 | $msg # The message to checksum |
335 | ) = @_; |
336 | my ($len_msg, # Length of the message |
337 | $num_short, # The number of short words in the message |
338 | $short, # One short word |
339 | $chk # The checksum |
340 | ); |
341 | |
342 | $len_msg = length($msg); |
343 | $num_short = int($len_msg / 2); |
344 | $chk = 0; |
345 | foreach $short (unpack("S$num_short", $msg)) |
346 | { |
347 | $chk += $short; |
348 | } # Add the odd byte in |
349 | $chk += (unpack("C", substr($msg, $len_msg - 1, 1)) << 8) if $len_msg % 2; |
350 | $chk = ($chk >> 16) + ($chk & 0xffff); # Fold high into low |
351 | return(~(($chk >> 16) + $chk) & 0xffff); # Again and complement |
a3b93737 |
352 | } |
353 | |
787ecdfa |
354 | |
b124990b |
355 | # Description: Perform a tcp echo ping. Since a tcp connection is |
356 | # host specific, we have to open and close each connection here. We |
357 | # can't just leave a socket open. Because of the robust nature of |
358 | # tcp, it will take a while before it gives up trying to establish a |
359 | # connection. Therefore, we use select() on a non-blocking socket to |
360 | # check against our timeout. No data bytes are actually |
361 | # sent since the successful establishment of a connection is proof |
362 | # enough of the reachability of the remote host. Also, tcp is |
363 | # expensive and doesn't need our help to add to the overhead. |
364 | |
365 | sub ping_tcp |
787ecdfa |
366 | { |
e82f584b |
367 | my ($self, |
368 | $ip, # Packed IP number of the host |
369 | $timeout # Seconds after which ping times out |
370 | ) = @_; |
371 | my ($ret # The return value |
372 | ); |
373 | |
374 | $@ = ""; $! = 0; |
375 | $ret = $self -> tcp_connect( $ip, $timeout); |
ef73e1db |
376 | $ret = 1 if $! == ECONNREFUSED; # Connection refused |
e82f584b |
377 | $self->{"fh"}->close(); |
378 | return $ret; |
787ecdfa |
379 | } |
380 | |
b124990b |
381 | sub tcp_connect |
787ecdfa |
382 | { |
e82f584b |
383 | my ($self, |
384 | $ip, # Packed IP number of the host |
385 | $timeout # Seconds after which connect times out |
386 | ) = @_; |
387 | my ($saddr); # Packed IP and Port |
b124990b |
388 | |
e82f584b |
389 | $saddr = sockaddr_in($self->{"port_num"}, $ip); |
b124990b |
390 | |
e82f584b |
391 | my $ret = 0; # Default to unreachable |
b124990b |
392 | |
e82f584b |
393 | my $do_socket = sub { |
394 | socket($self->{"fh"}, PF_INET, SOCK_STREAM, $self->{"proto_num"}) || |
395 | croak("tcp socket error - $!"); |
396 | if (defined $self->{"local_addr"} && |
397 | !CORE::bind($self->{"fh"}, sockaddr_in(0, $self->{"local_addr"}))) { |
398 | croak("tcp bind error - $!"); |
399 | } |
400 | }; |
401 | my $do_connect = sub { |
402 | eval { |
403 | die $! unless connect($self->{"fh"}, $saddr); |
404 | $self->{"ip"} = $ip; |
405 | $ret = 1; |
406 | }; |
407 | $ret; |
408 | }; |
409 | |
410 | if ($^O =~ /Win32/i) { |
411 | |
412 | # Buggy Winsock API doesn't allow us to use alarm() calls. |
413 | # Hence, if our OS is Windows, we need to create a separate |
414 | # process to do the blocking connect attempt. |
415 | |
416 | $| = 1; # Clear buffer prior to fork to prevent duplicate flushing. |
417 | my $pid = fork; |
418 | if (!$pid) { |
419 | if (!defined $pid) { |
420 | # Fork did not work |
421 | warn "Win32 Fork error: $!"; |
422 | return 0; |
b124990b |
423 | } |
b124990b |
424 | &{ $do_socket }(); |
425 | |
e82f584b |
426 | # Try a slow blocking connect() call |
427 | # and report the status to the pipe. |
428 | if ( &{ $do_connect }() ) { |
429 | $self->{"fh"}->close(); |
430 | # No error |
431 | exit 0; |
b124990b |
432 | } else { |
e82f584b |
433 | # Pass the error status to the parent |
434 | exit $!; |
b124990b |
435 | } |
e82f584b |
436 | } |
b124990b |
437 | |
e82f584b |
438 | &{ $do_socket }(); |
439 | |
440 | my $patience = &time() + $timeout; |
441 | |
442 | require POSIX; |
443 | my ($child); |
444 | $? = 0; |
445 | # Wait up to the timeout |
446 | # And clean off the zombie |
447 | do { |
448 | $child = waitpid($pid, &POSIX::WNOHANG); |
449 | $! = $? >> 8; |
450 | $@ = $!; |
451 | select(undef, undef, undef, 0.1); |
452 | } while &time() < $patience && $child != $pid; |
453 | |
454 | if ($child == $pid) { |
455 | # Since she finished within the timeout, |
456 | # it is probably safe for me to try it too |
b124990b |
457 | &{ $do_connect }(); |
e82f584b |
458 | } else { |
459 | # Time must have run out. |
460 | $@ = "Timed out!"; |
461 | # Put that choking client out of its misery |
462 | kill "KILL", $pid; |
463 | # Clean off the zombie |
464 | waitpid($pid, 0); |
465 | $ret = 0; |
b124990b |
466 | } |
e82f584b |
467 | } else { # Win32 |
468 | # Otherwise don't waste the resources to fork |
469 | |
470 | &{ $do_socket }(); |
471 | |
472 | $SIG{'ALRM'} = sub { die "Timed out!"; }; |
473 | alarm($timeout); # Interrupt connect() if we have to |
474 | |
475 | &{ $do_connect }(); |
476 | alarm(0); |
477 | } |
787ecdfa |
478 | |
e82f584b |
479 | return $ret; |
787ecdfa |
480 | } |
481 | |
482 | # This writes the given string to the socket and then reads it |
483 | # back. It returns 1 on success, 0 on failure. |
484 | sub tcp_echo |
485 | { |
e82f584b |
486 | my $self = shift; |
487 | my $timeout = shift; |
488 | my $pingstring = shift; |
489 | |
490 | my $ret = undef; |
491 | my $time = &time(); |
492 | my $wrstr = $pingstring; |
493 | my $rdstr = ""; |
494 | |
495 | eval <<'EOM'; |
496 | do { |
497 | my $rin = ""; |
498 | vec($rin, $self->{"fh"}->fileno(), 1) = 1; |
499 | |
500 | my $rout = undef; |
501 | if($wrstr) { |
502 | $rout = ""; |
503 | vec($rout, $self->{"fh"}->fileno(), 1) = 1; |
504 | } |
505 | |
506 | if(select($rin, $rout, undef, ($time + $timeout) - &time())) { |
507 | |
508 | if($rout && vec($rout,$self->{"fh"}->fileno(),1)) { |
509 | my $num = syswrite($self->{"fh"}, $wrstr); |
510 | if($num) { |
511 | # If it was a partial write, update and try again. |
512 | $wrstr = substr($wrstr,$num); |
513 | } else { |
514 | # There was an error. |
515 | $ret = 0; |
516 | } |
517 | } |
518 | |
519 | if(vec($rin,$self->{"fh"}->fileno(),1)) { |
520 | my $reply; |
521 | if(sysread($self->{"fh"},$reply,length($pingstring)-length($rdstr))) { |
522 | $rdstr .= $reply; |
523 | $ret = 1 if $rdstr eq $pingstring; |
524 | } else { |
525 | # There was an error. |
526 | $ret = 0; |
527 | } |
528 | } |
529 | |
530 | } |
531 | } until &time() > ($time + $timeout) || defined($ret); |
787ecdfa |
532 | EOM |
533 | |
e82f584b |
534 | return $ret; |
787ecdfa |
535 | } |
536 | |
787ecdfa |
537 | |
787ecdfa |
538 | |
787ecdfa |
539 | |
540 | # Description: Perform a stream ping. If the tcp connection isn't |
541 | # already open, it opens it. It then sends some data and waits for |
542 | # a reply. It leaves the stream open on exit. |
543 | |
544 | sub ping_stream |
545 | { |
e82f584b |
546 | my ($self, |
547 | $ip, # Packed IP number of the host |
548 | $timeout # Seconds after which ping times out |
549 | ) = @_; |
072620d9 |
550 | |
e82f584b |
551 | # Open the stream if it's not already open |
552 | if(!defined $self->{"fh"}->fileno()) { |
553 | $self->tcp_connect($ip, $timeout) or return 0; |
554 | } |
787ecdfa |
555 | |
e82f584b |
556 | croak "tried to switch servers while stream pinging" |
557 | if $self->{"ip"} ne $ip; |
558 | |
559 | return $self->tcp_echo($timeout, $pingstring); |
787ecdfa |
560 | } |
561 | |
562 | # Description: opens the stream. You would do this if you want to |
563 | # separate the overhead of opening the stream from the first ping. |
564 | |
565 | sub open |
566 | { |
e82f584b |
567 | my ($self, |
568 | $host, # Host or IP address |
569 | $timeout # Seconds after which open times out |
570 | ) = @_; |
571 | |
572 | my ($ip); # Packed IP number of the host |
573 | $ip = inet_aton($host); |
574 | $timeout = $self->{"timeout"} unless $timeout; |
575 | |
576 | if($self->{"proto"} eq "stream") { |
577 | if(defined($self->{"fh"}->fileno())) { |
578 | croak("socket is already open"); |
579 | } else { |
580 | $self->tcp_connect($ip, $timeout); |
b124990b |
581 | } |
e82f584b |
582 | } |
072620d9 |
583 | } |
584 | |
b124990b |
585 | |
a3b93737 |
586 | # Description: Perform a udp echo ping. Construct a message of |
587 | # at least the one-byte sequence number and any additional data bytes. |
588 | # Send the message out and wait for a message to come back. If we |
589 | # get a message, make sure all of its parts match. If they do, we are |
590 | # done. Otherwise go back and wait for the message until we run out |
591 | # of time. Return the result of our efforts. |
592 | |
49afa5f6 |
593 | use constant UDP_FLAGS => 0; # Nothing special on send or recv |
594 | |
a3b93737 |
595 | sub ping_udp |
596 | { |
e82f584b |
597 | my ($self, |
598 | $ip, # Packed IP number of the host |
599 | $timeout # Seconds after which ping times out |
600 | ) = @_; |
601 | |
602 | my ($saddr, # sockaddr_in with port and ip |
603 | $ret, # The return value |
604 | $msg, # Message to be echoed |
605 | $finish_time, # Time ping should be finished |
e82f584b |
606 | $done, # Set to 1 when we are done pinging |
607 | $rbits, # Read bits, filehandles for reading |
608 | $nfound, # Number of ready filehandles found |
609 | $from_saddr, # sockaddr_in of sender |
610 | $from_msg, # Characters echoed by $host |
611 | $from_port, # Port message was echoed from |
612 | $from_ip # Packed IP number of sender |
613 | ); |
614 | |
615 | $saddr = sockaddr_in($self->{"port_num"}, $ip); |
616 | $self->{"seq"} = ($self->{"seq"} + 1) % 256; # Increment sequence |
617 | $msg = chr($self->{"seq"}) . $self->{"data"}; # Add data if any |
618 | send($self->{"fh"}, $msg, UDP_FLAGS, $saddr); # Send it |
619 | |
620 | $rbits = ""; |
621 | vec($rbits, $self->{"fh"}->fileno(), 1) = 1; |
622 | $ret = 0; # Default to unreachable |
623 | $done = 0; |
e82f584b |
624 | $finish_time = &time() + $timeout; # Ping needs to be done by then |
625 | while (!$done && $timeout > 0) |
626 | { |
627 | $nfound = select($rbits, undef, undef, $timeout); # Wait for response |
628 | $timeout = $finish_time - &time(); # Get remaining time |
629 | |
630 | if (!defined($nfound)) # Hmm, a strange error |
a3b93737 |
631 | { |
e82f584b |
632 | $ret = undef; |
633 | $done = 1; |
a3b93737 |
634 | } |
e82f584b |
635 | elsif ($nfound) # A packet is waiting |
636 | { |
637 | $from_msg = ""; |
638 | $from_saddr = recv($self->{"fh"}, $from_msg, 1500, UDP_FLAGS) |
639 | or last; # For example an unreachable host will make recv() fail. |
640 | ($from_port, $from_ip) = sockaddr_in($from_saddr); |
641 | if (($from_ip eq $ip) && # Does the packet check out? |
642 | ($from_port == $self->{"port_num"}) && |
643 | ($from_msg eq $msg)) |
644 | { |
645 | $ret = 1; # It's a winner |
646 | $done = 1; |
647 | } |
648 | } |
649 | else # Oops, timed out |
650 | { |
651 | $done = 1; |
652 | } |
653 | } |
a5a165b1 |
654 | return $ret; |
b124990b |
655 | } |
a0d0e21e |
656 | |
a3b93737 |
657 | # Description: Close the connection unless we are using the tcp |
658 | # protocol, since it will already be closed. |
659 | |
660 | sub close |
661 | { |
e82f584b |
662 | my ($self) = @_; |
a3b93737 |
663 | |
e82f584b |
664 | $self->{"fh"}->close() unless $self->{"proto"} eq "tcp"; |
a3b93737 |
665 | } |
666 | |
667 | |
a0d0e21e |
668 | 1; |
8e07c86e |
669 | __END__ |
670 | |
8e07c86e |
671 | =head1 NAME |
672 | |
a3b93737 |
673 | Net::Ping - check a remote host for reachability |
8e07c86e |
674 | |
564e2e78 |
675 | $Id: Ping.pm,v 1.34 2002/05/06 17:37:54 rob Exp $ |
b124990b |
676 | |
8e07c86e |
677 | =head1 SYNOPSIS |
678 | |
679 | use Net::Ping; |
8e07c86e |
680 | |
a3b93737 |
681 | $p = Net::Ping->new(); |
682 | print "$host is alive.\n" if $p->ping($host); |
683 | $p->close(); |
684 | |
685 | $p = Net::Ping->new("icmp"); |
49afa5f6 |
686 | $p->bind($my_addr); # Specify source interface of pings |
a3b93737 |
687 | foreach $host (@host_array) |
688 | { |
689 | print "$host is "; |
690 | print "NOT " unless $p->ping($host, 2); |
691 | print "reachable.\n"; |
692 | sleep(1); |
693 | } |
694 | $p->close(); |
b124990b |
695 | |
a3b93737 |
696 | $p = Net::Ping->new("tcp", 2); |
b124990b |
697 | # Try connecting to the www port instead of the echo port |
698 | $p->{port_num} = getservbyname("http", "tcp"); |
a3b93737 |
699 | while ($stop_time > time()) |
700 | { |
701 | print "$host not reachable ", scalar(localtime()), "\n" |
702 | unless $p->ping($host); |
703 | sleep(300); |
704 | } |
705 | undef($p); |
b124990b |
706 | |
e82f584b |
707 | # High precision syntax (requires Time::HiRes) |
708 | $p = Net::Ping->new(); |
709 | $p->hires(); |
710 | ($ret, $duration, $ip) = $p->ping($host, 5.5); |
711 | printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n", 1000 * $duration) |
712 | if $ret; |
713 | $p->close(); |
714 | |
a3b93737 |
715 | # For backward compatibility |
716 | print "$host is alive.\n" if pingecho($host); |
8e07c86e |
717 | |
a3b93737 |
718 | =head1 DESCRIPTION |
8e07c86e |
719 | |
a3b93737 |
720 | This module contains methods to test the reachability of remote |
721 | hosts on a network. A ping object is first created with optional |
722 | parameters, a variable number of hosts may be pinged multiple |
723 | times and then the connection is closed. |
724 | |
b124990b |
725 | You may choose one of four different protocols to use for the |
726 | ping. The "udp" protocol is the default. Note that a live remote host |
727 | may still fail to be pingable by one or more of these protocols. For |
728 | example, www.microsoft.com is generally alive but not pingable. |
787ecdfa |
729 | |
b124990b |
730 | With the "tcp" protocol the ping() method attempts to establish a |
731 | connection to the remote host's echo port. If the connection is |
732 | successfully established, the remote host is considered reachable. No |
733 | data is actually echoed. This protocol does not require any special |
734 | privileges but has higher overhead than the other two protocols. |
072620d9 |
735 | |
b124990b |
736 | Specifying the "udp" protocol causes the ping() method to send a udp |
a3b93737 |
737 | packet to the remote host's echo port. If the echoed packet is |
738 | received from the remote host and the received packet contains the |
739 | same data as the packet that was sent, the remote host is considered |
740 | reachable. This protocol does not require any special privileges. |
b124990b |
741 | It should be borne in mind that, for a udp ping, a host |
787ecdfa |
742 | will be reported as unreachable if it is not running the |
b124990b |
743 | appropriate echo service. For Unix-like systems see L<inetd(8)> |
744 | for more information. |
787ecdfa |
745 | |
b124990b |
746 | If the "icmp" protocol is specified, the ping() method sends an icmp |
747 | echo message to the remote host, which is what the UNIX ping program |
748 | does. If the echoed message is received from the remote host and |
749 | the echoed information is correct, the remote host is considered |
750 | reachable. Specifying the "icmp" protocol requires that the program |
751 | be run as root or that the program be setuid to root. |
787ecdfa |
752 | |
b124990b |
753 | If the "external" protocol is specified, the ping() method attempts to |
754 | use the C<Net::Ping::External> module to ping the remote host. |
755 | C<Net::Ping::External> interfaces with your system's default C<ping> |
756 | utility to perform the ping, and generally produces relatively |
787ecdfa |
757 | accurate results. If C<Net::Ping::External> if not installed on your |
758 | system, specifying the "external" protocol will result in an error. |
edc5bd88 |
759 | |
a3b93737 |
760 | =head2 Functions |
761 | |
762 | =over 4 |
763 | |
764 | =item Net::Ping->new([$proto [, $def_timeout [, $bytes]]]); |
765 | |
766 | Create a new ping object. All of the parameters are optional. $proto |
767 | specifies the protocol to use when doing a ping. The current choices |
768 | are "tcp", "udp" or "icmp". The default is "udp". |
769 | |
770 | If a default timeout ($def_timeout) in seconds is provided, it is used |
771 | when a timeout is not given to the ping() method (below). The timeout |
772 | must be greater than 0 and the default, if not specified, is 5 seconds. |
773 | |
774 | If the number of data bytes ($bytes) is given, that many data bytes |
775 | are included in the ping packet sent to the remote host. The number of |
776 | data bytes is ignored if the protocol is "tcp". The minimum (and |
777 | default) number of data bytes is 1 if the protocol is "udp" and 0 |
778 | otherwise. The maximum number of data bytes that can be specified is |
779 | 1024. |
780 | |
e82f584b |
781 | =item $p->hires( { 0 | 1 } ); |
782 | |
783 | Causes this module to use Time::HiRes module, allowing milliseconds |
784 | to be returned by subsequent calls to ping(). |
785 | |
49afa5f6 |
786 | =item $p->bind($local_addr); |
787 | |
788 | Sets the source address from which pings will be sent. This must be |
789 | the address of one of the interfaces on the local host. $local_addr |
790 | may be specified as a hostname or as a text IP address such as |
791 | "192.168.1.1". |
792 | |
793 | If the protocol is set to "tcp", this method may be called any |
794 | number of times, and each call to the ping() method (below) will use |
795 | the most recent $local_addr. If the protocol is "icmp" or "udp", |
796 | then bind() must be called at most once per object, and (if it is |
797 | called at all) must be called before the first call to ping() for that |
798 | object. |
799 | |
a3b93737 |
800 | =item $p->ping($host [, $timeout]); |
801 | |
802 | Ping the remote host and wait for a response. $host can be either the |
803 | hostname or the IP number of the remote host. The optional timeout |
804 | must be greater than 0 seconds and defaults to whatever was specified |
e82f584b |
805 | when the ping object was created. Returns a success flag. If the |
806 | hostname cannot be found or there is a problem with the IP number, the |
807 | success flag returned will be undef. Otherwise, the success flag will |
808 | be 1 if the host is reachable and 0 if it is not. For most practical |
809 | purposes, undef and 0 and can be treated as the same case. In array |
810 | context, the elapsed time is also returned. The elapsed time value will |
811 | be a float, as retuned by the Time::HiRes::time() function, if hires() |
812 | has been previously called, otherwise it is returned as an integer. |
b124990b |
813 | |
814 | =item $p->open($host); |
815 | |
816 | When you are using the stream protocol, this call pre-opens the |
817 | tcp socket. It's only necessary to do this if you want to |
818 | provide a different timeout when creating the connection, or |
819 | remove the overhead of establishing the connection from the |
820 | first ping. If you don't call C<open()>, the connection is |
821 | automatically opened the first time C<ping()> is called. |
787ecdfa |
822 | This call simply does nothing if you are using any protocol other |
823 | than stream. |
824 | |
a3b93737 |
825 | =item $p->close(); |
826 | |
827 | Close the network connection for this ping object. The network |
828 | connection is also closed by "undef $p". The network connection is |
829 | automatically closed if the ping object goes out of scope (e.g. $p is |
830 | local to a subroutine and you leave the subroutine). |
831 | |
832 | =item pingecho($host [, $timeout]); |
833 | |
834 | To provide backward compatibility with the previous version of |
835 | Net::Ping, a pingecho() subroutine is available with the same |
836 | functionality as before. pingecho() uses the tcp protocol. The |
837 | return values and parameters are the same as described for the ping() |
838 | method. This subroutine is obsolete and may be removed in a future |
839 | version of Net::Ping. |
8e07c86e |
840 | |
a3b93737 |
841 | =back |
8e07c86e |
842 | |
b124990b |
843 | =head1 WARNING |
844 | |
845 | pingecho() or a ping object with the tcp protocol use alarm() to |
846 | implement the timeout. So, don't use alarm() in your program while |
847 | you are using pingecho() or a ping object with the tcp protocol. The |
848 | udp and icmp protocols do not use alarm() to implement the timeout. |
849 | |
a3b93737 |
850 | =head1 NOTES |
8e07c86e |
851 | |
a3b93737 |
852 | There will be less network overhead (and some efficiency in your |
853 | program) if you specify either the udp or the icmp protocol. The tcp |
854 | protocol will generate 2.5 times or more traffic for each ping than |
855 | either udp or icmp. If many hosts are pinged frequently, you may wish |
856 | to implement a small wait (e.g. 25ms or more) between each ping to |
857 | avoid flooding your network with packets. |
8e07c86e |
858 | |
a3b93737 |
859 | The icmp protocol requires that the program be run as root or that it |
787ecdfa |
860 | be setuid to root. The other protocols do not require special |
861 | privileges, but not all network devices implement tcp or udp echo. |
8e07c86e |
862 | |
a3b93737 |
863 | Local hosts should normally respond to pings within milliseconds. |
864 | However, on a very congested network it may take up to 3 seconds or |
865 | longer to receive an echo packet from the remote host. If the timeout |
866 | is set too low under these conditions, it will appear that the remote |
867 | host is not reachable (which is almost the truth). |
8e07c86e |
868 | |
a3b93737 |
869 | Reachability doesn't necessarily mean that the remote host is actually |
787ecdfa |
870 | functioning beyond its ability to echo packets. tcp is slightly better |
871 | at indicating the health of a system than icmp because it uses more |
872 | of the networking stack to respond. |
8e07c86e |
873 | |
a3b93737 |
874 | Because of a lack of anything better, this module uses its own |
875 | routines to pack and unpack ICMP packets. It would be better for a |
876 | separate module to be written which understands all of the different |
877 | kinds of ICMP packets. |
8e07c86e |
878 | |
49afa5f6 |
879 | =head1 AUTHORS |
b124990b |
880 | |
e82f584b |
881 | Current maintainer: |
49afa5f6 |
882 | bbb@cpan.org (Rob Brown) |
b124990b |
883 | |
e82f584b |
884 | External protocol: |
885 | colinm@cpan.org (Colin McMillen) |
886 | |
b124990b |
887 | Stream protocol: |
888 | bronson@trestle.com (Scott Bronson) |
889 | |
890 | Original pingecho(): |
891 | karrer@bernina.ethz.ch (Andreas Karrer) |
892 | pmarquess@bfsec.bt.co.uk (Paul Marquess) |
893 | |
894 | Original Net::Ping author: |
895 | mose@ns.ccsn.edu (Russell Mosemann) |
896 | |
b124990b |
897 | =head1 COPYRIGHT |
898 | |
e82f584b |
899 | Copyright (c) 2002, Rob Brown. All rights reserved. |
49afa5f6 |
900 | |
e82f584b |
901 | Copyright (c) 2001, Colin McMillen. All rights reserved. |
b124990b |
902 | |
903 | This program is free software; you may redistribute it and/or |
904 | modify it under the same terms as Perl itself. |
905 | |
a3b93737 |
906 | =cut |