1#! @PATH_PERL@ -w 2 3# John Hay -- John.Hay@icomtek.csir.co.za / jhay@FreeBSD.org 4 5use Socket; 6use Getopt::Std; 7use vars qw($opt_n $opt_m); 8 9$ntpq = "ntpq"; 10 11getopts('nm:'); 12 13$dodns = 1; 14$dodns = 0 if (defined($opt_n)); 15 16$max_hosts = (defined($opt_m) ? $opt_m : 99); 17$max_hosts = 0 if ( $max_hosts !~ /^\d+$/ ); 18$nb_host = 1; 19 20$host = shift; 21$host ||= "127.0.0.1"; 22 23for (;;) { 24 $nb_host++; 25 $rootdelay = 0; 26 $rootdispersion = 0; 27 $stratum = 255; 28 $cmd = "$ntpq -n -c rv $host"; 29 open(PH, $cmd . "|") || die "failed to start command $cmd: $!"; 30 while (<PH>) { 31 $stratum = $1 if (/stratum=(\d+)/); 32 $peer = $1 if (/peer=(\d+)/); 33 # Very old servers report phase and not offset. 34 $offset = $1 if (/(?:offset|phase)=([^\s,]+)/); 35 $rootdelay = $1 if (/rootdelay=([^\s,]+)/); 36 $rootdispersion = $1 if (/rootdispersion=([^\s,]+)/); 37 $refid = $1 if (/refid=([^\s,]+)/); 38 } 39 close(PH) || die "$cmd failed"; 40 last if ($stratum == 255); 41 $offset /= 1000; 42 $syncdistance = ($rootdispersion + ($rootdelay / 2)) / 1000; 43 $dhost = $host; 44 # Only do lookups of IPv4 addresses. The standard lookup functions 45 # of perl only do IPv4 and I don't know if we should require extras. 46 if ($dodns && $host =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) { 47 $iaddr = inet_aton($host); 48 $name = (gethostbyaddr($iaddr, AF_INET))[0]; 49 $dhost = $name if (defined($name)); 50 } 51 printf("%s: stratum %d, offset %f, synch distance %f", 52 $dhost, $stratum, $offset, $syncdistance); 53 printf(", refid '%s'", $refid) if ($stratum == 1); 54 printf("\n"); 55 last if ($stratum == 0 || $stratum == 1 || $stratum == 16); 56 last if ($refid =~ /^127\.127\.\d{1,3}\.\d{1,3}$/); 57 last if ($nb_host > $max_hosts); 58 59 $cmd = "$ntpq -n -c \"pstat $peer\" $host"; 60 open(PH, $cmd . "|") || die "failed to start command $cmd: $!"; 61 $thost = ""; 62 while (<PH>) { 63 $thost = $1, last if (/srcadr=(\S+),/); 64 } 65 close(PH) || die "$cmd failed"; 66 last if ($thost eq ""); 67 last if ($thost =~ /^127\.127\.\d{1,3}\.\d{1,3}$/); 68 $host = $thost; 69} 70 71