#!/bin/perl -w
use Socket;
use FileHandle;   #for autoflush
use POSIX;        #for the W functions

if (@ARGV < 1 || @ARGV > 2) {
	die "$0: requires hostname and optional port number\n";
}

$ip = inet_aton($ARGV[0]) or die "$0: inet_aton failed\n";

if (@ARGV < 2) {
	$port = getservbyname('telnet', 'tcp') or die "$0: couldn't find telnet port\n";
}

else {
	if ($ARGV[1] !~ /^\d+$/) {
		die "$0: second argument must be a port number\n";
	}

	$port = $ARGV[1];
}

socket(S, PF_INET, SOCK_STREAM, 0) or die "$0: $!\n";
S->autoflush();
$address = sockaddr_in($port, $ip) or die "$0: sockaddr_in failed\n";

$dotted = inet_ntoa($ip);
print "Trying $dotted...\n";

connect(S, $address) or die "$0: $!\n";

@host = gethostbyaddr($ip, AF_INET) or die "$0: gethostbyaddr failed\n";
print "Connected to $host[0].\n",
	"Escape character is '^d'.\n";

$pid = fork();
defined $pid or die "$0: $!";

if ($pid == 0) {
	while (($c = getc(S)) ne '') {
		print $c;
	}

	print STDERR "Connection closed by foreign host.\n";
	exit 0;
}

#The parent will copy from the stdin to the server.
while (($c = getc()) ne '') {
	print S $c;
}

shutdown(S, SHUT_RDWR) or die "$0: $!";

$pid = wait();
if (WIFEXITED($?)) {
	print "My child's exit status was ", WEXITSTATUS($?), ".\n";
}

elsif (WIFSIGNALED($?)) {
	print "My child was terminated by signal number ", WTERMSIG($?), ".\n";
}

elsif (WIFSTOPPED($?)) {
	print "My child was stopped by signal number ", WSTOPSIG($?), ".\n";
}

else {
	die "$0: couldn't find out how child ended up\n";
}

exit 0;
