# fix possibly unqualified or truncated hostname, given the fqdn of the
# host that we got the information from.
#
sub fix_hostname {
    local ($host, $origin) = @_;
    local ($fqdn, $dot, $old, $frag, $n, $trial);

    # First see if the name (or IP address) is in the DNS.
    if ($host =~ /\./ && ($fqdn = &dns_host($host))) {
	return $fqdn;
    }

    # Can't do anything else for IP addresses.
    if ($host =~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {
	return "";
    }

    # Can't do hostname completion when the originator is an IP address.
    if ($origin =~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {
	return $host;
    }

    # Assume an unqualified name is in the same domain as the originator.
    # 
    if (($dot = index($host, ".")) < $[) {
	return &dns_host($host . substr($origin, index($origin, ".")));
    }
    $old = $dot;

    # Assume the hostname is trucated.
    foreach $trial ($origin, ".mil", ".edu", ".gov", ".net", ".org", ".com") {
        for ($dot = $old; length($frag = substr($host,$dot-$[)) > 1; $dot += $n) {
            # Match .fragment with (upper domain) of trial domain.
            if (($n = index($trial, $frag)) >= $[) {
                if ($fqdn = &dns_host(substr($host, $[, $dot - $[) . substr($trial, $n))) {
		    return $fqdn;
		}
	    }
            # Strip lowest .subdomain from .fragment and retry.
            last if (($n = index(substr($frag, $[ + 1), ".") + 1 - $[) < 1);
        }
    }

    # Unable to fix the hostname.
    #
    return "";
}

#  Lookup the FQDN for a host name or address; return "" if not found.
#
sub dns_host {
 
	local($host) = @_;
	 
	if ($opt_v) {
		print STDERR "dns_host: trying: $host\n";
	}

	# do cache lookup first
	if (defined($dns_cache{$host})) {
		return($dns_cache{$host});
		}
	 
	# if host is name, not ip address
	if ($host !~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/) {
		($host, $aliases, $type, $len, @ip) = gethostbyname("$host.");
		($a,$b,$c,$d) = unpack('C4',$ip[0]);
		}
	else {
		($a,$b,$c,$d) = split(/\./, $host);
		@ip = ($a,$b,$c,$d);
		($host) = gethostbyaddr(pack("C4", @ip), &AF_INET);
		}
	 
	# success:
	if ($host && @ip) {
		return $dns_cache{$host} = $host;
		}
	# failure:
	else {
		return $dns_cache{$host} = "";
		}
	}

sub AF_INET {2;}

1;
