#/usr/bin/perl -w
# traceroute.pl: Emulates /usr/sbin/traceroute via ping.
# 
($osname, $hostname, $osversion) = split (/ /, `uname -a`);

$PINGPATH = "/usr/sbin/ping";
# $PINGPATH = "/bin/ping";
$PINGOPT  = "-t";

$PINGEXIT = "Time exceeded in transit";
$PINGDONE = "is alive";

$MAXREAD = 10;
$MAXHOPS = 25;

$KNOWNOS = "sunos";
$KNOWNVER= "5.6";
 
# show usage unless we have a host to ping to
die "usage: pmtracerout host\n" unless $ARGV[0];

# some simple error checking
die <<PINGNOTFOUND unless -x $PINGPATH;
Could not find ping executable in '$PINGPATH'! 
Please locate it manually and update the source of this script accordingly.
PINGNOTFOUND

$supported = (($KNOWNOS =~ /\Q$osname/i) and ($KNOWNVER =~ /\Q$osversion/));
warn <<WRONGOS unless $supported;
Note: This OS version ($osname $osversion) is not supported. If this script
hangs or fails in any other way, check the ping options used in this script 
and see if they are supported in your version of ping. You have been warned.
WRONGOS

# loop over $MAXHOPS hops
for ($wait = 1; $wait <= $MAXHOPS; $wait++) { 
  # assemble ping command
  $command = "$PINGPATH $PINGOPT $wait $ARGV[0] 1";
  #warn "Issuing '$command'\n";

  open (PING, "$command |");

  $i = 0;
  while ($line = <PING>) {
    # print ":>$line";
    last if $line =~ /$PINGEXIT/;
    if ($line =~ /$PINGDONE/) {
      print "$wait. $line";
      exit;
    } 
    $i++;
    die <<STRINGNOTFOUND if $i >= $MAXREAD;
Error: Could not find timeout string in first $MAXREAD lines of ping output. 
Exiting...
STRINGNOTFOUND
  }
  sleep 2;
  close (PING);

  if ($line =~ /from (.*)$/) {
    print "$wait. $1\n";
  } else {
    # seems we didn't find anything in the ping output.
    warn "Error: Could not find timeout string in ping output\n";
  }
}

