1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Errno qw( EINPROGRESS );
7use IO::Poll;
8use IO::Socket::IP;
9use Net::LibAsyncNS;
10use Socket qw( SOCK_STREAM );
11
12my $host    = shift @ARGV or die "Need HOST\n";
13my $service = shift @ARGV or die "Need SERVICE\n";
14
15my $poll = IO::Poll->new;
16
17my $asyncns = Net::LibAsyncNS->new( 1 );
18my $asyncns_fh = $asyncns->new_handle_for_fd;
19
20my $q = $asyncns->getaddrinfo( $host, $service, { socktype => SOCK_STREAM } );
21
22$poll->mask( $asyncns_fh => POLLIN );
23
24while( !$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
34my ( $err, @peeraddrinfo ) = $asyncns->getaddrinfo_done( $q );
35$err and die "getaddrinfo() - $!";
36
37my $socket = IO::Socket::IP->new(
38   PeerAddrInfo => \@peeraddrinfo,
39   Blocking     => 0,
40) or die "Cannot construct socket - $@";
41
42$poll->mask( $socket => POLLOUT );
43
44while(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
53printf STDERR "Connected to %s:%s\n", $socket->peerhost_service;
54
55$poll->mask( \*STDIN => POLLIN );
56$poll->mask( $socket => POLLIN );
57
58while(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}
74