#!/usr/bin/perl

=begin metadata

Name: whois
Description: internet domain name and network number directory service
Author: Yiorgos Adamopoulos, adamo@ieee.org
License:

=end metadata

=cut

# Sample whois(1) client for PPT.
#
# Yiorgos Adamopoulos, adamo@ieee.org, Mon Mar 22 15:28:05 EET 1999
#                                      Mon Mar 22 16:24:23 EET 1999
#
# The command line switches are taken from the FreeBSD whois(1) page
# Added a -6 switch for 6BONE (whois.6bone.net)
# Added a -g switch for .gov (whois.nic.gov)

use strict;

use Getopt::Std qw(getopts);
use IO::Socket;

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my (%opt, $host);
getopts('6adprgh:', \%opt) or usage();
usage() unless @ARGV;

set_host('whois.arin.net')     if $opt{'a'};
set_host('whois.nic.mil')      if $opt{'d'};
set_host('whois.apnic.net')    if $opt{'p'};
set_host('whois.ripe.net')     if $opt{'r'};
set_host('whois.nic.gov')      if $opt{'g'};
set_host('whois.6bone.net')    if $opt{'6'};
set_host($opt{'h'})            if $opt{'h'};
set_host('whois.internic.net') unless defined $host;

$| = 1;

foreach my $domain (@ARGV) {
    whois($domain);
}
exit EX_SUCCESS;

sub whois {
    my $domain = shift;
    if (length($domain) == 0 || $domain !~ m/\S/) {
        warn "empty domain name\n";
        exit EX_FAILURE;
    }
    my $sock = IO::Socket::INET->new(
        PeerAddr => $host,
        PeerPort => 43,
        Proto => 'tcp',
    );
    unless ($sock) {
        warn "$host: $IO::Socket::errstr\n";
        exit EX_FAILURE;
    }
    print {$sock} "$domain\r\n";
    while (my $line = <$sock>) {
        print $line;
    }
    close $sock;
}

sub usage {
    warn "usage: whois [-6adprg] [-h host] domain...\n";
    exit EX_FAILURE;
}

sub set_host {
    if (defined $host) {
        warn "ambiguous host specification\n";
        exit EX_FAILURE;
    }
    $host = shift;
}

=encoding utf8

=head1 NAME

whois - Internet domain name and network number directory service
