#!/usr/bin/perl -w
use strict;
use Socket;

my ( $remote, $port );
my ( $iaddr, $paddr, $proto, $line );

$remote  = shift || 'localhost';
$port    = shift || 2342;  # random port
if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
die "No port" unless $port;
$iaddr   = inet_aton($remote)               || die "no host: $remote";
$paddr   = sockaddr_in($port, $iaddr);
$proto   = getprotobyname('tcp');
socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
connect(SOCK, $paddr)    || die "connect: $!";

# print SOCK "\n\nget foo bar\n\n";
send(SOCK, "get termsize\n", 0);
my ( $cols, $rows ) = ( 0, 0 );
if (defined(my $line = <SOCK>)) {
    print $line;
    if ( $line =~ /^cols:\s(\d*?),\srows:\s(\d*?)$/ ) {
	$cols = $1;
	$rows = $2;
	print "termsize: ok $cols $rows\n";
    } else {
	print "termsize: error";
    }
}

close (SOCK)            || die "close: $!";

exit;

