# whoisquery.pl
#
# Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998, 1999 by RIPE NCC
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of the author not be
# used in advertising or publicity pertaining to distribution of the
# software without specific, written prior permission.
#
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
# AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
# AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# $Id: whoisqry.pl,v 2.5 1999/10/06 16:41:27 marek Exp $
#
#	$RCSfile: whoisqry.pl,v $
#	$Revision: 2.5 $
#	$Author: marek $
#	$Date: 1999/10/06 16:41:27 $

# This is a very simple whois client module

use Socket;

sub getwhoisportandproto {
    local($port)=@_;
    
    local($name,$aliases,$proto);

    if ($port=~ /^\d+$/) {
       $proto="tcp";
    }
    else {
        ($name,$aliases,$port,$proto)=getservbyname("whois", "tcp");
        die "cannot find portnumber for \'whois\' service" if (!$port);
        #print STDERR "-$port-$proto-";
    }

    ($name,$aliases,$proto)=getprotobyname($proto);

    return ($port,$proto);
    
}

sub initwhoisqry {
    local($host, $port, $string)=@_;
    
    local($proto,$address);
    
    if ($host=~ /^\s*\d+\.\d+\.\d+\.\d+\s*$/) {
       $address=pack("C4",split(/\./,$host));
    }
    else {
       $address=(gethostbyname($host))[4];
    }

    unless ($address) {
       return "Connect to host: $host port: $port failed: host unknown";
    }
    
    # find valid port and protocol number for whois service
    
    #print "*$port*\n";
    
    ($port,$proto)=&getwhoisportandproto($port);
    
    #
    # connect
    
    socket(WHOIS_S, PF_INET, SOCK_STREAM, $proto) || die "socket creation failed\n";
    
    if (connect(WHOIS_S, sockaddr_in ($port, $address))) {
    
       #
       # no buffering
    
       local($oldhandle)=select(WHOIS_S); $| = 1; select($oldhandle);

       #
       # print options
    
       print WHOIS_S $string, "\n";
       
       return "";
    
    }
    else {
    
       return "Connect to host: $host port: $port failed: $!";

    }
    
    #
    # returning a socket doesn't work, so we use the global var ...
    #
    # I found how to this but haven't had time to do the change.
    #
    # return (WHOIS_S);

}

1;
