| 1 |
#!/usr/bin/perl |
| 2 |
|
| 3 |
use v5.14; |
| 4 |
use warnings; |
| 5 |
|
| 6 |
use Errno qw( EINPROGRESS ); |
| 7 |
use IO::Poll; |
| 8 |
use IO::Socket::IP; |
| 9 |
use Net::LibAsyncNS; |
| 10 |
use Socket qw( SOCK_STREAM ); |
| 11 |
|
| 12 |
my $host = shift @ARGV or die "Need HOST\n"; |
| 13 |
my $service = shift @ARGV or die "Need SERVICE\n"; |
| 14 |
|
| 15 |
my $poll = IO::Poll->new; |
| 16 |
|
| 17 |
my $asyncns = Net::LibAsyncNS->new( 1 ); |
| 18 |
my $asyncns_fh = $asyncns->new_handle_for_fd; |
| 19 |
|
| 20 |
my $q = $asyncns->getaddrinfo( $host, $service, { socktype => SOCK_STREAM } ); |
| 21 |
|
| 22 |
$poll->mask( $asyncns_fh => POLLIN ); |
| 23 |
|
| 24 |
while( !$q->isdone ) { |
| 25 |
$poll->poll( undef ); |
| 26 |
|
| 27 |
if( $poll->events( $asyncns_fh ) ) { |
| 28 |
$asyncns->wait( 0 ); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
$poll->mask( $asyncns_fh => 0 ); |
| 33 |
|
| 34 |
my ( $err, @peeraddrinfo ) = $asyncns->getaddrinfo_done( $q ); |
| 35 |
$err and die "getaddrinfo() - $!"; |
| 36 |
|
| 37 |
my $socket = IO::Socket::IP->new( |
| 38 |
PeerAddrInfo => \@peeraddrinfo, |
| 39 |
Blocking => 0, |
| 40 |
) or die "Cannot construct socket - $IO::Socket::errstr"; |
| 41 |
|
| 42 |
$poll->mask( $socket => POLLOUT ); |
| 43 |
|
| 44 |
while(1) { |
| 45 |
$poll->poll( undef ); |
| 46 |
|
| 47 |
if( $poll->events( $socket ) & POLLOUT ) { |
| 48 |
last if $socket->connect; |
| 49 |
die "Cannot connect - $!" unless $! == EINPROGRESS; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
printf STDERR "Connected to %s:%s\n", $socket->peerhost_service; |
| 54 |
|
| 55 |
$poll->mask( \*STDIN => POLLIN ); |
| 56 |
$poll->mask( $socket => POLLIN ); |
| 57 |
|
| 58 |
while(1) { |
| 59 |
$poll->poll( undef ); |
| 60 |
|
| 61 |
if( $poll->events( \*STDIN ) ) { |
| 62 |
my $ret = STDIN->sysread( my $buffer, 8192 ); |
| 63 |
defined $ret or die "Cannot read STDIN - $!\n"; |
| 64 |
$ret or last; |
| 65 |
$socket->syswrite( $buffer ); |
| 66 |
} |
| 67 |
if( $poll->events( $socket ) ) { |
| 68 |
my $ret = $socket->sysread( my $buffer, 8192 ); |
| 69 |
defined $ret or die "Cannot read socket - $!\n"; |
| 70 |
$ret or last; |
| 71 |
STDOUT->syswrite( $buffer ); |
| 72 |
} |
| 73 |
} |