1#!/usr/bin/perl
2
3use v5;
4use strict;
5use warnings;
6
7use Test::More;
8
9use IO::Socket::IP;
10
11use IO::Socket::INET;
12use Socket qw( inet_aton inet_ntoa pack_sockaddr_in unpack_sockaddr_in );
13use Errno qw( EINPROGRESS EWOULDBLOCK );
14
15# Some odd locations like BSD jails might not like INADDR_LOOPBACK. We'll
16# establish a baseline first to test against
17my $INADDR_LOOPBACK = do {
18   socket my $sockh, PF_INET, SOCK_STREAM, 0 or die "Cannot socket(PF_INET) - $!";
19   bind $sockh, pack_sockaddr_in( 0, inet_aton( "127.0.0.1" ) ) or die "Cannot bind() - $!";
20   ( unpack_sockaddr_in( getsockname $sockh ) )[1];
21};
22my $INADDR_LOOPBACK_HOST = inet_ntoa( $INADDR_LOOPBACK );
23if( $INADDR_LOOPBACK ne INADDR_LOOPBACK ) {
24   diag( "Testing with INADDR_LOOPBACK=$INADDR_LOOPBACK_HOST; this may be because of odd networking" );
25}
26
27my $testserver = IO::Socket::INET->new(
28   Listen    => 1,
29   LocalHost => "127.0.0.1",
30   Type      => SOCK_STREAM,
31) or die "Cannot listen on PF_INET - $@";
32
33my $socket = IO::Socket::IP->new(
34   PeerHost    => "127.0.0.1",
35   PeerService => $testserver->sockport,
36   Type        => SOCK_STREAM,
37   Blocking    => 0,
38);
39
40ok( defined $socket, 'IO::Socket::IP->new( Blocking => 0 ) constructs a socket' ) or
41   diag( "  error was $@" );
42
43ok( defined $socket->fileno, '$socket has a fileno immediately after construction' );
44
45while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
46   my $wvec = '';
47   vec( $wvec, fileno $socket, 1 ) = 1;
48   my $evec = '';
49   vec( $evec, fileno $socket, 1 ) = 1;
50
51   select( undef, $wvec, $evec, undef ) or die "Cannot select() - $!";
52}
53
54ok( !$!, 'Repeated ->connect eventually succeeds' );
55
56is( $socket->sockdomain, AF_INET,     '$socket->sockdomain' );
57is( $socket->socktype,   SOCK_STREAM, '$socket->socktype' );
58
59is_deeply( [ unpack_sockaddr_in $socket->peername ],
60           [ unpack_sockaddr_in $testserver->sockname ],
61           '$socket->peername' );
62
63is( $socket->peerhost, $INADDR_LOOPBACK_HOST, '$socket->peerhost' );
64is( $socket->peerport, $testserver->sockport, '$socket->peerport' );
65
66ok( !$socket->blocking, '$socket->blocking' );
67
68done_testing;
69