#! /usr/local/bin/perl
eval 'exec perl -S $0 ${1+"$@"} ;' unless 1;
#
# find a dotted domain name somewhere on a line, look up its ip address
# and append the address to the line.
#
# if -i is given, replace the IP name inplace with as much of the
#       ip address as fits (instead of appending it).
# if -f is given, list all ip addresses, else just the first
# if -d # is given, domain names must have that many dots to be considered
# if -c # is given, don't cache dns lookups (probably for testing DNS)
# if -t # is given, just emit lines with regexp match highlighted (for testing)
#
# Corey Satten, corey @ cac.washington.edu, 7/23/98
# http://staff.washington.edu/corey

$dots = 1;		# default minimum number of dots in domain name
$BO = "\033[7m";	# bold
$NO = "\033[m";		# normal

while ($ARGV[0] =~ /^-./) {
    $_ = shift(@ARGV);
    if (/^-i$/) { $inplace = 1; next; }
    if (/^-f$/) { $all_addrs = 1; next; }
    if (/^-t$/) { $test = 1; next; }
    if (/^-c$/) { $no_cache = 1; next; }
    if (/^-d$/) { $dots = shift; next; }
    die ("unknown flag");
    }

while (<>) {
    if ($_ =~ /\b([a-zA-Z][-+_\w]*)((\.[a-zA-Z][-+_\w]*){$dots,})\b */o) {
	if ($test) { s//$BO$&$NO/; print; next; }
	$host = "$1$2";
	if ($no_cache || !defined $cache{$host} ) {
	    ($name,$aliases,$addrtype,$length,@addrs) = gethostbyname("$host");
	    if ($#addrs >= 0) {
		$addr = "";
		for ($i = 0; $i <= ($all_addrs ? 0 : $#addrs); ++$i) {
		    $addr .= ", " if (length($addr));
		    $addr .= sprintf("%d.%d.%d.%d", unpack("CCCC", $addrs[$i]));
		    }
		$cache{$host} = $addr;
		}
	    }

	if (defined $cache{$host}) {
	    $addr = $cache{$host};
	    if ($inplace) {
		$len = length($&) - 1;
		$_ = $` . sprintf("%-${len}.${len}s ", $addr) . $';
		}
	    else {
		s/$/	$addr/;
		}
	    }
	}
    print;
    }
