#!/usr/local/bin/perl -w
#    client.pl
#      by Yoshioka Tsuneo(ke3057yt@ex.ecip.osaka-u.ac.jp)
#    Copy,Edit,Distribute FREE!
#


# please see /usr/include/sys/socket.h 
#     or /usr/include/linux/socket.h and so on. 
# eval("require 'sys/socket.h'");

#if($ENV{'OSTYPE'} =~ m/(linux|next)/i){
    $AF_INET=2;$SOCK_STREAM=1;
#}elsif($ENV{'OSTYPE'} =~ m#sun#i){
#    $AF_INET=2;$SOCK_STREAM=2;
#}else{
#    $AF_INET=2;$SOCK_STREAM=2;
#}
$SOCK_STREAM=1;


;# login server
;#    return value:1:OK, -1:NO
sub login_server {
    local(*S,$server,$port)=@_;
    local($host,$name,$sockaddr_t,$oldfh);
    local($aliases,$proto,$type,$len,$this,$that,$thisaddr,$thataddr);
    #print "logining to <$server>\n";
    if(!defined($server)){
        $err_msg="not defiled server";return -1;
        }
    if(!defined($port)){
        $err_msg="not defiled port";return -1;
        }

    # $AF_INET=2;$SOCK_STREAM=1;
    $sockaddr_t='S n a4 x8';
    chop($host=`hostname`);
    ($name,$aliases,$proto)=getprotobyname("tcp");
    ($name,$aliases,$type,$len,$thisaddr)=gethostbyname($host);
    ($name,$aliases,$type,$len,$thataddr)=gethostbyname($server);
#    print "name is <$name>\n";
    if($name eq ""){
	$err_msg="can't gethostbyname($server): $!";return -1;
    }
    $this=pack($sockaddr_t,$AF_INET,0,$thisaddr);
    $that=pack($sockaddr_t,$AF_INET,$port,$thataddr);
    if(!socket(S,$AF_INET,$SOCK_STREAM,$proto)){
        $err_msg="socket: $!";return -1;
    }
    if(!bind(S,$this)){
        $err_msg="bind: $!";return -1;
    }
    if(!connect(S,$that)){
        $err_msg="connect: $!";return -1;
    }
    $oldfh=select(S);$|=1;select($oldfh);
    1;
}
sub usage
{
    print "usage: $0 <server name> <port number>\n";
}
#------------main-----------------------------
if($0 eq __FILE__){
    if($#ARGV!=1){
	&usage();
	exit 1;
    }
    local($server)=$ARGV[0];
    local($port)=$ARGV[1];
    local(*S);
    $err=&login_server(*S,$server,$port);
    if($err==0){
	print $err_msg,"\n";
	exit 1;
    }
    while(<STDIN>){
	print S $_;
    }
    while(<S>){
	print $_;
    }
}
1;







