Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 lines
20 KiB

  1. package Net::Ping;
  2. # Author: [email protected] (Russell Mosemann)
  3. #
  4. # Authors of the original pingecho():
  5. # [email protected] (Andreas Karrer)
  6. # [email protected] (Paul Marquess)
  7. #
  8. # Copyright (c) 1996 Russell Mosemann. All rights reserved. This
  9. # program is free software; you may redistribute it and/or modify it
  10. # under the same terms as Perl itself.
  11. require 5.002;
  12. require Exporter;
  13. use strict;
  14. use vars qw(@ISA @EXPORT $VERSION
  15. $def_timeout $def_proto $max_datasize);
  16. use FileHandle;
  17. use Socket qw( SOCK_DGRAM SOCK_STREAM SOCK_RAW PF_INET
  18. inet_aton sockaddr_in );
  19. use Carp;
  20. @ISA = qw(Exporter);
  21. @EXPORT = qw(pingecho);
  22. $VERSION = 2.02;
  23. # Constants
  24. $def_timeout = 5; # Default timeout to wait for a reply
  25. $def_proto = "udp"; # Default protocol to use for pinging
  26. $max_datasize = 1024; # Maximum data bytes in a packet
  27. # Description: The pingecho() subroutine is provided for backward
  28. # compatibility with the original Net::Ping. It accepts a host
  29. # name/IP and an optional timeout in seconds. Create a tcp ping
  30. # object and try pinging the host. The result of the ping is returned.
  31. sub pingecho
  32. {
  33. my ($host, # Name or IP number of host to ping
  34. $timeout # Optional timeout in seconds
  35. ) = @_;
  36. my ($p); # A ping object
  37. $p = Net::Ping->new("tcp", $timeout);
  38. $p->ping($host); # Going out of scope closes the connection
  39. }
  40. # Description: The new() method creates a new ping object. Optional
  41. # parameters may be specified for the protocol to use, the timeout in
  42. # seconds and the size in bytes of additional data which should be
  43. # included in the packet.
  44. # After the optional parameters are checked, the data is constructed
  45. # and a socket is opened if appropriate. The object is returned.
  46. sub new
  47. {
  48. my ($this,
  49. $proto, # Optional protocol to use for pinging
  50. $timeout, # Optional timeout in seconds
  51. $data_size # Optional additional bytes of data
  52. ) = @_;
  53. my $class = ref($this) || $this;
  54. my $self = {};
  55. my ($cnt, # Count through data bytes
  56. $min_datasize # Minimum data bytes required
  57. );
  58. bless($self, $class);
  59. $proto = $def_proto unless $proto; # Determine the protocol
  60. croak("Protocol for ping must be \"tcp\", \"udp\" or \"icmp\"")
  61. unless $proto =~ m/^(tcp|udp|icmp)$/;
  62. $self->{"proto"} = $proto;
  63. $timeout = $def_timeout unless $timeout; # Determine the timeout
  64. croak("Default timeout for ping must be greater than 0 seconds")
  65. if $timeout <= 0;
  66. $self->{"timeout"} = $timeout;
  67. $min_datasize = ($proto eq "udp") ? 1 : 0; # Determine data size
  68. $data_size = $min_datasize unless defined($data_size) && $proto ne "tcp";
  69. croak("Data for ping must be from $min_datasize to $max_datasize bytes")
  70. if ($data_size < $min_datasize) || ($data_size > $max_datasize);
  71. $data_size-- if $self->{"proto"} eq "udp"; # We provide the first byte
  72. $self->{"data_size"} = $data_size;
  73. $self->{"data"} = ""; # Construct data bytes
  74. for ($cnt = 0; $cnt < $self->{"data_size"}; $cnt++)
  75. {
  76. $self->{"data"} .= chr($cnt % 256);
  77. }
  78. $self->{"seq"} = 0; # For counting packets
  79. if ($self->{"proto"} eq "udp") # Open a socket
  80. {
  81. $self->{"proto_num"} = (getprotobyname('udp'))[2] ||
  82. croak("Can't udp protocol by name");
  83. $self->{"port_num"} = (getservbyname('echo', 'udp'))[2] ||
  84. croak("Can't get udp echo port by name");
  85. $self->{"fh"} = FileHandle->new();
  86. socket($self->{"fh"}, &PF_INET(), &SOCK_DGRAM(),
  87. $self->{"proto_num"}) ||
  88. croak("udp socket error - $!");
  89. }
  90. elsif ($self->{"proto"} eq "icmp")
  91. {
  92. croak("icmp ping requires root privilege") if ($> and $^O ne 'VMS');
  93. $self->{"proto_num"} = (getprotobyname('icmp'))[2] ||
  94. croak("Can't get icmp protocol by name");
  95. $self->{"pid"} = $$ & 0xffff; # Save lower 16 bits of pid
  96. $self->{"fh"} = FileHandle->new();
  97. socket($self->{"fh"}, &PF_INET(), &SOCK_RAW(), $self->{"proto_num"}) ||
  98. croak("icmp socket error - $!");
  99. }
  100. elsif ($self->{"proto"} eq "tcp") # Just a file handle for now
  101. {
  102. $self->{"proto_num"} = (getprotobyname('tcp'))[2] ||
  103. croak("Can't get tcp protocol by name");
  104. $self->{"port_num"} = (getservbyname('echo', 'tcp'))[2] ||
  105. croak("Can't get tcp echo port by name");
  106. $self->{"fh"} = FileHandle->new();
  107. }
  108. return($self);
  109. }
  110. # Description: Ping a host name or IP number with an optional timeout.
  111. # First lookup the host, and return undef if it is not found. Otherwise
  112. # perform the specific ping method based on the protocol. Return the
  113. # result of the ping.
  114. sub ping
  115. {
  116. my ($self,
  117. $host, # Name or IP number of host to ping
  118. $timeout # Seconds after which ping times out
  119. ) = @_;
  120. my ($ip, # Packed IP number of $host
  121. $ret # The return value
  122. );
  123. croak("Usage: \$p->ping(\$host [, \$timeout])") unless @_ == 2 || @_ == 3;
  124. $timeout = $self->{"timeout"} unless $timeout;
  125. croak("Timeout must be greater than 0 seconds") if $timeout <= 0;
  126. $ip = inet_aton($host);
  127. return(undef) unless defined($ip); # Does host exist?
  128. if ($self->{"proto"} eq "udp")
  129. {
  130. $ret = $self->ping_udp($ip, $timeout);
  131. }
  132. elsif ($self->{"proto"} eq "icmp")
  133. {
  134. $ret = $self->ping_icmp($ip, $timeout);
  135. }
  136. elsif ($self->{"proto"} eq "tcp")
  137. {
  138. $ret = $self->ping_tcp($ip, $timeout);
  139. }
  140. else
  141. {
  142. croak("Unknown protocol \"$self->{proto}\" in ping()");
  143. }
  144. return($ret);
  145. }
  146. sub ping_icmp
  147. {
  148. my ($self,
  149. $ip, # Packed IP number of the host
  150. $timeout # Seconds after which ping times out
  151. ) = @_;
  152. my $ICMP_ECHOREPLY = 0; # ICMP packet types
  153. my $ICMP_ECHO = 8;
  154. my $icmp_struct = "C2 S3 A"; # Structure of a minimal ICMP packet
  155. my $subcode = 0; # No ICMP subcode for ECHO and ECHOREPLY
  156. my $flags = 0; # No special flags when opening a socket
  157. my $port = 0; # No port with ICMP
  158. my ($saddr, # sockaddr_in with port and ip
  159. $checksum, # Checksum of ICMP packet
  160. $msg, # ICMP packet to send
  161. $len_msg, # Length of $msg
  162. $rbits, # Read bits, filehandles for reading
  163. $nfound, # Number of ready filehandles found
  164. $finish_time, # Time ping should be finished
  165. $done, # set to 1 when we are done
  166. $ret, # Return value
  167. $recv_msg, # Received message including IP header
  168. $from_saddr, # sockaddr_in of sender
  169. $from_port, # Port packet was sent from
  170. $from_ip, # Packed IP of sender
  171. $from_type, # ICMP type
  172. $from_subcode, # ICMP subcode
  173. $from_chk, # ICMP packet checksum
  174. $from_pid, # ICMP packet id
  175. $from_seq, # ICMP packet sequence
  176. $from_msg # ICMP message
  177. );
  178. $self->{"seq"} = ($self->{"seq"} + 1) % 65536; # Increment sequence
  179. $checksum = 0; # No checksum for starters
  180. $msg = pack($icmp_struct . $self->{"data_size"}, $ICMP_ECHO, $subcode,
  181. $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"});
  182. $checksum = Net::Ping->checksum($msg);
  183. $msg = pack($icmp_struct . $self->{"data_size"}, $ICMP_ECHO, $subcode,
  184. $checksum, $self->{"pid"}, $self->{"seq"}, $self->{"data"});
  185. $len_msg = length($msg);
  186. $saddr = sockaddr_in($port, $ip);
  187. send($self->{"fh"}, $msg, $flags, $saddr); # Send the message
  188. $rbits = "";
  189. vec($rbits, $self->{"fh"}->fileno(), 1) = 1;
  190. $ret = 0;
  191. $done = 0;
  192. $finish_time = time() + $timeout; # Must be done by this time
  193. while (!$done && $timeout > 0) # Keep trying if we have time
  194. {
  195. $nfound = select($rbits, undef, undef, $timeout); # Wait for packet
  196. $timeout = $finish_time - time(); # Get remaining time
  197. if (!defined($nfound)) # Hmm, a strange error
  198. {
  199. $ret = undef;
  200. $done = 1;
  201. }
  202. elsif ($nfound) # Got a packet from somewhere
  203. {
  204. $recv_msg = "";
  205. $from_saddr = recv($self->{"fh"}, $recv_msg, 1500, $flags);
  206. ($from_port, $from_ip) = sockaddr_in($from_saddr);
  207. ($from_type, $from_subcode, $from_chk,
  208. $from_pid, $from_seq, $from_msg) =
  209. unpack($icmp_struct . $self->{"data_size"},
  210. substr($recv_msg, length($recv_msg) - $len_msg,
  211. $len_msg));
  212. if (($from_type == $ICMP_ECHOREPLY) &&
  213. ($from_ip eq $ip) &&
  214. ($from_pid == $self->{"pid"}) && # Does the packet check out?
  215. ($from_seq == $self->{"seq"}))
  216. {
  217. $ret = 1; # It's a winner
  218. $done = 1;
  219. }
  220. }
  221. else # Oops, timed out
  222. {
  223. $done = 1;
  224. }
  225. }
  226. return($ret)
  227. }
  228. # Description: Do a checksum on the message. Basically sum all of
  229. # the short words and fold the high order bits into the low order bits.
  230. sub checksum
  231. {
  232. my ($class,
  233. $msg # The message to checksum
  234. ) = @_;
  235. my ($len_msg, # Length of the message
  236. $num_short, # The number of short words in the message
  237. $short, # One short word
  238. $chk # The checksum
  239. );
  240. $len_msg = length($msg);
  241. $num_short = $len_msg / 2;
  242. $chk = 0;
  243. foreach $short (unpack("S$num_short", $msg))
  244. {
  245. $chk += $short;
  246. } # Add the odd byte in
  247. $chk += unpack("C", substr($msg, $len_msg - 1, 1)) if $len_msg % 2;
  248. $chk = ($chk >> 16) + ($chk & 0xffff); # Fold high into low
  249. return(~(($chk >> 16) + $chk) & 0xffff); # Again and complement
  250. }
  251. # Description: Perform a tcp echo ping. Since a tcp connection is
  252. # host specific, we have to open and close each connection here. We
  253. # can't just leave a socket open. Because of the robust nature of
  254. # tcp, it will take a while before it gives up trying to establish a
  255. # connection. Therefore, we have to set the alarm to break out of the
  256. # connection sooner if the timeout expires. No data bytes are actually
  257. # sent since the successful establishment of a connection is proof
  258. # enough of the reachability of the remote host. Also, tcp is
  259. # expensive and doesn't need our help to add to the overhead.
  260. sub ping_tcp
  261. {
  262. my ($self,
  263. $ip, # Packed IP number of the host
  264. $timeout # Seconds after which ping times out
  265. ) = @_;
  266. my ($saddr, # sockaddr_in with port and ip
  267. $ret # The return value
  268. );
  269. socket($self->{"fh"}, &PF_INET(), &SOCK_STREAM(), $self->{"proto_num"}) ||
  270. croak("tcp socket error - $!");
  271. $saddr = sockaddr_in($self->{"port_num"}, $ip);
  272. $SIG{'ALRM'} = sub { die };
  273. alarm($timeout); # Interrupt connect() if we have to
  274. $ret = 0; # Default to unreachable
  275. eval <<'EOM' ;
  276. return unless connect($self->{"fh"}, $saddr);
  277. $ret = 1;
  278. EOM
  279. alarm(0);
  280. $self->{"fh"}->close();
  281. return($ret);
  282. }
  283. # Description: Perform a udp echo ping. Construct a message of
  284. # at least the one-byte sequence number and any additional data bytes.
  285. # Send the message out and wait for a message to come back. If we
  286. # get a message, make sure all of its parts match. If they do, we are
  287. # done. Otherwise go back and wait for the message until we run out
  288. # of time. Return the result of our efforts.
  289. sub ping_udp
  290. {
  291. my ($self,
  292. $ip, # Packed IP number of the host
  293. $timeout # Seconds after which ping times out
  294. ) = @_;
  295. my $flags = 0; # Nothing special on open
  296. my ($saddr, # sockaddr_in with port and ip
  297. $ret, # The return value
  298. $msg, # Message to be echoed
  299. $finish_time, # Time ping should be finished
  300. $done, # Set to 1 when we are done pinging
  301. $rbits, # Read bits, filehandles for reading
  302. $nfound, # Number of ready filehandles found
  303. $from_saddr, # sockaddr_in of sender
  304. $from_msg, # Characters echoed by $host
  305. $from_port, # Port message was echoed from
  306. $from_ip # Packed IP number of sender
  307. );
  308. $saddr = sockaddr_in($self->{"port_num"}, $ip);
  309. $self->{"seq"} = ($self->{"seq"} + 1) % 256; # Increment sequence
  310. $msg = chr($self->{"seq"}) . $self->{"data"}; # Add data if any
  311. send($self->{"fh"}, $msg, $flags, $saddr); # Send it
  312. $rbits = "";
  313. vec($rbits, $self->{"fh"}->fileno(), 1) = 1;
  314. $ret = 0; # Default to unreachable
  315. $done = 0;
  316. $finish_time = time() + $timeout; # Ping needs to be done by then
  317. while (!$done && $timeout > 0)
  318. {
  319. $nfound = select($rbits, undef, undef, $timeout); # Wait for response
  320. $timeout = $finish_time - time(); # Get remaining time
  321. if (!defined($nfound)) # Hmm, a strange error
  322. {
  323. $ret = undef;
  324. $done = 1;
  325. }
  326. elsif ($nfound) # A packet is waiting
  327. {
  328. $from_msg = "";
  329. $from_saddr = recv($self->{"fh"}, $from_msg, 1500, $flags);
  330. ($from_port, $from_ip) = sockaddr_in($from_saddr);
  331. if (($from_ip eq $ip) && # Does the packet check out?
  332. ($from_port == $self->{"port_num"}) &&
  333. ($from_msg eq $msg))
  334. {
  335. $ret = 1; # It's a winner
  336. $done = 1;
  337. }
  338. }
  339. else # Oops, timed out
  340. {
  341. $done = 1;
  342. }
  343. }
  344. return($ret);
  345. }
  346. # Description: Close the connection unless we are using the tcp
  347. # protocol, since it will already be closed.
  348. sub close
  349. {
  350. my ($self) = @_;
  351. $self->{"fh"}->close() unless $self->{"proto"} eq "tcp";
  352. }
  353. 1;
  354. __END__
  355. =head1 NAME
  356. Net::Ping - check a remote host for reachability
  357. =head1 SYNOPSIS
  358. use Net::Ping;
  359. $p = Net::Ping->new();
  360. print "$host is alive.\n" if $p->ping($host);
  361. $p->close();
  362. $p = Net::Ping->new("icmp");
  363. foreach $host (@host_array)
  364. {
  365. print "$host is ";
  366. print "NOT " unless $p->ping($host, 2);
  367. print "reachable.\n";
  368. sleep(1);
  369. }
  370. $p->close();
  371. $p = Net::Ping->new("tcp", 2);
  372. while ($stop_time > time())
  373. {
  374. print "$host not reachable ", scalar(localtime()), "\n"
  375. unless $p->ping($host);
  376. sleep(300);
  377. }
  378. undef($p);
  379. # For backward compatibility
  380. print "$host is alive.\n" if pingecho($host);
  381. =head1 DESCRIPTION
  382. This module contains methods to test the reachability of remote
  383. hosts on a network. A ping object is first created with optional
  384. parameters, a variable number of hosts may be pinged multiple
  385. times and then the connection is closed.
  386. You may choose one of three different protocols to use for the ping.
  387. With the "tcp" protocol the ping() method attempts to establish a
  388. connection to the remote host's echo port. If the connection is
  389. successfully established, the remote host is considered reachable. No
  390. data is actually echoed. This protocol does not require any special
  391. privileges but has higher overhead than the other two protocols.
  392. Specifying the "udp" protocol causes the ping() method to send a udp
  393. packet to the remote host's echo port. If the echoed packet is
  394. received from the remote host and the received packet contains the
  395. same data as the packet that was sent, the remote host is considered
  396. reachable. This protocol does not require any special privileges.
  397. If the "icmp" protocol is specified, the ping() method sends an icmp
  398. echo message to the remote host, which is what the UNIX ping program
  399. does. If the echoed message is received from the remote host and
  400. the echoed information is correct, the remote host is considered
  401. reachable. Specifying the "icmp" protocol requires that the program
  402. be run as root or that the program be setuid to root.
  403. =head2 Functions
  404. =over 4
  405. =item Net::Ping->new([$proto [, $def_timeout [, $bytes]]]);
  406. Create a new ping object. All of the parameters are optional. $proto
  407. specifies the protocol to use when doing a ping. The current choices
  408. are "tcp", "udp" or "icmp". The default is "udp".
  409. If a default timeout ($def_timeout) in seconds is provided, it is used
  410. when a timeout is not given to the ping() method (below). The timeout
  411. must be greater than 0 and the default, if not specified, is 5 seconds.
  412. If the number of data bytes ($bytes) is given, that many data bytes
  413. are included in the ping packet sent to the remote host. The number of
  414. data bytes is ignored if the protocol is "tcp". The minimum (and
  415. default) number of data bytes is 1 if the protocol is "udp" and 0
  416. otherwise. The maximum number of data bytes that can be specified is
  417. 1024.
  418. =item $p->ping($host [, $timeout]);
  419. Ping the remote host and wait for a response. $host can be either the
  420. hostname or the IP number of the remote host. The optional timeout
  421. must be greater than 0 seconds and defaults to whatever was specified
  422. when the ping object was created. If the hostname cannot be found or
  423. there is a problem with the IP number, undef is returned. Otherwise,
  424. 1 is returned if the host is reachable and 0 if it is not. For all
  425. practical purposes, undef and 0 and can be treated as the same case.
  426. =item $p->close();
  427. Close the network connection for this ping object. The network
  428. connection is also closed by "undef $p". The network connection is
  429. automatically closed if the ping object goes out of scope (e.g. $p is
  430. local to a subroutine and you leave the subroutine).
  431. =item pingecho($host [, $timeout]);
  432. To provide backward compatibility with the previous version of
  433. Net::Ping, a pingecho() subroutine is available with the same
  434. functionality as before. pingecho() uses the tcp protocol. The
  435. return values and parameters are the same as described for the ping()
  436. method. This subroutine is obsolete and may be removed in a future
  437. version of Net::Ping.
  438. =back
  439. =head1 WARNING
  440. pingecho() or a ping object with the tcp protocol use alarm() to
  441. implement the timeout. So, don't use alarm() in your program while
  442. you are using pingecho() or a ping object with the tcp protocol. The
  443. udp and icmp protocols do not use alarm() to implement the timeout.
  444. =head1 NOTES
  445. There will be less network overhead (and some efficiency in your
  446. program) if you specify either the udp or the icmp protocol. The tcp
  447. protocol will generate 2.5 times or more traffic for each ping than
  448. either udp or icmp. If many hosts are pinged frequently, you may wish
  449. to implement a small wait (e.g. 25ms or more) between each ping to
  450. avoid flooding your network with packets.
  451. The icmp protocol requires that the program be run as root or that it
  452. be setuid to root. The tcp and udp protocols do not require special
  453. privileges, but not all network devices implement the echo protocol
  454. for tcp or udp.
  455. Local hosts should normally respond to pings within milliseconds.
  456. However, on a very congested network it may take up to 3 seconds or
  457. longer to receive an echo packet from the remote host. If the timeout
  458. is set too low under these conditions, it will appear that the remote
  459. host is not reachable (which is almost the truth).
  460. Reachability doesn't necessarily mean that the remote host is actually
  461. functioning beyond its ability to echo packets.
  462. Because of a lack of anything better, this module uses its own
  463. routines to pack and unpack ICMP packets. It would be better for a
  464. separate module to be written which understands all of the different
  465. kinds of ICMP packets.
  466. =cut