#!/usr/local/bin/perl
#
# whois.pl (c) 1998 by Yutaka Oiwa
# slight modificated version of Harada's get.pl
# (c) 1996 Masanori Harada
#

$timeout = 120;
$AF_INET = 2;
$SOCK_STREAM = 1;

$them = 'whois.nic.ad.jp';

($target) = @ARGV;

if ($target eq '-h') {
    ($t, $them, $target) = @ARGV; # 
}

if ($target eq '') {
    print STDERR "usage: $0 [ -h host ] name\n";
    exit 0;
}
 
$port = 'whois';

if($them =~ m@(.*):(\d+)@){
	$them = $1;
	$port = $2;
}

# print "\n\n --- '$them':'$port' '$target'\n";

$sockaddr = 'S n a4 x8';
chop($hostname = `hostname`);

($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $port) = getservbyname($port, 'tcp')
    unless $port =~ /^\d+$/;;
($name, $aliases, $type, $len, $thisaddr) =  gethostbyname($hostname);
if($them =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/){
    $thataddr = pack('c4', $1, $2, $3, $4);
}else{
    ($name, $aliases, $type, $len, $thataddr) =  gethostbyname($them);
}
$thataddr || die "$0:\n\tUnknown host: $them\n";

$this = pack($sockaddr, $AF_INET, 0, $thisaddr);
$that = pack($sockaddr, $AF_INET, $port, $thataddr);

$runscript = <<'_EOT_';
socket(S, $AF_INET, $SOCK_STREAM, $proto) || die "socket: $!";
# bind(S, $this) || die "bind: $!";
$SIG{'ALRM'} = 'timed_out';
alarm($timeout);
connect(S,$that) || die "connect: $!";
alarm($timeout);
select(S); $| = 1; 
select(STDOUT); $| = 1;

print S "$target\n";

$SIG{'ALRM'} = 'IGNORE';
alarm(0);
while(<S>){			# body
    print;
}
print "\n";
_EOT_

eval $runscript;
print STDERR "$0:\n\t$@\n" if($@);

exit 0;

sub timed_out {
    local($sig) = @_;

    die "\nConnection timed out. (SIG$sig)\n";
}
