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