#!/usr/local/bin/perl

# perkel.pl 20070722.01
# Jeremy Kister - http://jeremy.kister.net./
# MOTD: Fred Thompson '08!!

use strict;

my $DEBUG = 1;
my $arg = shift;

my $hostname = fcrdns($arg);

if($hostname){
		print "$arg has FCrDNS to $hostname\n";
}else{
		print "$arg has no FCrDNS\n";
}

sub fcrdns {
	my $ipaddr = shift;
	
	if($ipaddr =~ /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/){ # close enough
		my ($hostname,$good);
		eval {
			local $SIG{ALRM} = sub { die "fcrdns timeout during reverse.\n"; };
			alarm(3);
			$hostname = (gethostbyaddr(pack('C4',split('\.',$ipaddr)),2))[0];
			warn "hostname: $hostname\n" if($DEBUG);
			alarm(0);
		};
		alarm(0);
		warn "$@\n" if($@);

		if($hostname){
			eval {
				local $SIG{ALRM} = sub { die "fcrdns timeout during forward.\n"; };
				alarm(3);
				my @addrs = (gethostbyname($hostname))[4];
				foreach my $packed (@addrs){ # could be multiple ip addresses per hostname
					my($a,$b,$c,$d) = unpack('C4',$packed);
					warn "addr: $a.$b.$c.$d\n" if($DEBUG);
					if($arg eq "$a.$b.$c.$d"){
						$good = 1; # if either matches, call it good
						last;
					}
				}
				alarm(0);
			};
			alarm(0);
			if($@){
				warn "$@\n";
			}elsif($good){
				return($hostname);
			}
		}
	}else{
		warn "argument not an ip address\n";
	}
	return;
}
