#!/usr/bin/perl -w
# require 5.002;
use strict;
use Socket qw (getaddrinfo getnameinfo AF_UNSPEC SOCK_STREAM SOL_SOCKET SO_REUSEADDR NI_NUMERICHOST NI_NUMERICSERV ) ;
my ($remote,$port, $iaddr, $paddr, $proto, $line);

my $user = getpwuid($<);

$remote  = shift || 'localhost';
$port    = shift || 2345;  # random port
if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
die "No port" unless $port;

&connect_address($remote,$port);

syswrite SOCK, "$user\n"; #  or die "syswrite $!\n";
while (<SOCK>) {
    print ;
}

close SOCK           or die "close: $!";


sub connect_address {
   my ($host0,$port0) = @_;

    my ($err,@res) = getaddrinfo($host0, $port0, {socktype=>SOCK_STREAM});
    my $family1 = -1;
    my ($err1, $host, $port);
    for my $res (@res) { 
        my ($family, $socktype, $proto, $saddr, $canonname) = ( $res->{family} , $res->{socktype}, $res->{protocol}, $res->{addr}, $res->{canonname} );

        ($err1, $host, $port) = getnameinfo($saddr,NI_NUMERICHOST | NI_NUMERICSERV);
        print STDERR "Trying to connect to $host : $port...\n";

        socket(SOCK, $family, $socktype, $proto) || next;
        if (connect(SOCK, $saddr)) { 
            print STDERR "connected to $host port $port\n";
            return;
        }
        close(SOCK);
    }
    die "connect attempt failed\n";
}