File Coverage

blib/lib/IO/Socket/IP.pm
Criterion Covered Total %
statement 282 353 79.8
branch 134 214 62.6
condition 64 114 56.1
subroutine 33 41 80.4
pod 19 23 82.6
total 532 745 71.4


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2010-2024 -- leonerd@leonerd.org.uk
5              
6             package IO::Socket::IP 0.43;
7              
8 22     22   5272937 use v5.14;
  22         93  
9 22     22   144 use warnings;
  22         164  
  22         1461  
10              
11 22     22   156 use base qw( IO::Socket );
  22         40  
  22         13761  
12              
13 22     22   531886 use Carp;
  22         96  
  22         2114  
14              
15 22         7088 use Socket 1.97 qw(
16             getaddrinfo getnameinfo
17             sockaddr_family
18             AF_INET
19             AI_PASSIVE
20             IPPROTO_TCP IPPROTO_UDP
21             IPPROTO_IPV6 IPV6_V6ONLY
22             NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV
23             SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR
24             SOCK_DGRAM SOCK_STREAM
25             SOL_SOCKET
26 22     22   133 );
  22         440  
27             my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined
28             my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0;
29 22     22   14227 use POSIX qw( dup2 );
  22         166235  
  22         164  
30 22     22   38803 use Errno qw( EINVAL EINPROGRESS EISCONN ENOTCONN ETIMEDOUT EWOULDBLOCK EOPNOTSUPP );
  22         106  
  22         3489  
31              
32 22     22   194 use constant HAVE_MSWIN32 => ( $^O eq "MSWin32" );
  22         115  
  22         2386  
33              
34             # At least one OS (Android) is known not to have getprotobyname()
35 22     22   156 use constant HAVE_GETPROTOBYNAME => defined eval { getprotobyname( "tcp" ) };
  22         42  
  22         37  
  22         119418  
36              
37             my $IPv6_re = do {
38             # translation of RFC 3986 3.2.2 ABNF to re
39             my $IPv4address = do {
40             my $dec_octet = q<(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])>;
41             qq<$dec_octet(?: \\. $dec_octet){3}>;
42             };
43             my $IPv6address = do {
44             my $h16 = qq<[0-9A-Fa-f]{1,4}>;
45             my $ls32 = qq<(?: $h16 : $h16 | $IPv4address)>;
46             qq<(?:
47             (?: $h16 : ){6} $ls32
48             | :: (?: $h16 : ){5} $ls32
49             | (?: $h16 )? :: (?: $h16 : ){4} $ls32
50             | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32
51             | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32
52             | (?: (?: $h16 : ){0,3} $h16 )? :: $h16 : $ls32
53             | (?: (?: $h16 : ){0,4} $h16 )? :: $ls32
54             | (?: (?: $h16 : ){0,5} $h16 )? :: $h16
55             | (?: (?: $h16 : ){0,6} $h16 )? ::
56             )>
57             };
58             qr<$IPv6address>xo;
59             };
60              
61             =head1 NAME
62              
63             C - Family-neutral IP socket supporting both IPv4 and IPv6
64              
65             =head1 SYNOPSIS
66              
67             =for highlighter language=perl
68              
69             use IO::Socket::IP;
70              
71             my $sock = IO::Socket::IP->new(
72             PeerHost => "www.google.com",
73             PeerPort => "http",
74             Type => SOCK_STREAM,
75             ) or die "Cannot construct socket - $IO::Socket::errstr";
76              
77             my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
78             ( $sock->sockdomain == PF_INET ) ? "IPv4" :
79             "unknown";
80              
81             printf "Connected to google via %s\n", $familyname;
82              
83             =head1 DESCRIPTION
84              
85             This module provides a protocol-independent way to use IPv4 and IPv6 sockets,
86             intended as a replacement for L. Most constructor arguments
87             and methods are provided in a backward-compatible way. For a list of known
88             differences, see the C INCOMPATIBILITIES section below.
89              
90             It uses the C function to convert hostnames and service names
91             or port numbers into sets of possible addresses to connect to or listen on.
92             This allows it to work for IPv6 where the system supports it, while still
93             falling back to IPv4-only on systems which don't.
94              
95             =head1 REPLACING C DEFAULT BEHAVIOUR
96              
97             By placing C<-register> in the import list to C, it will
98             register itself with L as the class that handles C. It
99             will also ask to handle C as well, provided that constant is
100             available.
101              
102             Changing C's default behaviour means that calling the
103             C constructor with either C or C as the
104             C parameter will yield an C object.
105              
106             use IO::Socket::IP -register;
107              
108             my $sock = IO::Socket->new(
109             Domain => PF_INET6,
110             LocalHost => "::1",
111             Listen => 1,
112             ) or die "Cannot create socket - $IO::Socket::errstr\n";
113              
114             print "Created a socket of type " . ref($sock) . "\n";
115              
116             Note that C<-register> is a global setting that applies to the entire program;
117             it cannot be applied only for certain callers, removed, or limited by lexical
118             scope.
119              
120             =cut
121              
122             sub import
123             {
124 21     21   213 my $pkg = shift;
125 21         39 my @symbols;
126              
127 21         91 foreach ( @_ ) {
128 1 50       5 if( $_ eq "-register" ) {
129 1         14 IO::Socket::IP::_ForINET->register_domain( AF_INET );
130 1 50       14 IO::Socket::IP::_ForINET6->register_domain( $AF_INET6 ) if defined $AF_INET6;
131             }
132             else {
133 0         0 push @symbols, $_;
134             }
135             }
136              
137 21         78 @_ = ( $pkg, @symbols );
138 21         167 goto &IO::Socket::import;
139             }
140              
141             # Convenient capability test function
142             {
143             my $can_disable_v6only;
144             sub CAN_DISABLE_V6ONLY
145             {
146 0 0   0 0 0 return $can_disable_v6only if defined $can_disable_v6only;
147              
148 0 0       0 socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or
149             die "Cannot socket(PF_INET6) - $!";
150              
151 0 0 0     0 if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) {
    0          
152 0 0       0 if( $^O eq "dragonfly") {
153             # dragonflybsd 6.4 lies about successfully turning this off
154 0 0       0 if( getsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY ) {
155 0         0 return $can_disable_v6only = 0;
156             }
157             }
158 0         0 return $can_disable_v6only = 1;
159             }
160             elsif( $! == EINVAL || $! == EOPNOTSUPP ) {
161 0         0 return $can_disable_v6only = 0;
162             }
163             else {
164 0         0 die "Cannot setsockopt() - $!";
165             }
166             }
167             }
168              
169             =head1 CONSTRUCTORS
170              
171             =cut
172              
173             =head2 new
174              
175             $sock = IO::Socket::IP->new( %args )
176              
177             Creates a new C object, containing a newly created socket
178             handle according to the named arguments passed. The recognised arguments are:
179              
180             =over 8
181              
182             =item PeerHost => STRING
183              
184             =item PeerService => STRING
185              
186             Hostname and service name for the peer to C to. The service name
187             may be given as a port number, as a decimal string.
188              
189             =item PeerAddr => STRING
190              
191             =item PeerPort => STRING
192              
193             For symmetry with the accessor methods and compatibility with
194             C, these are accepted as synonyms for C and
195             C respectively.
196              
197             =item PeerAddrInfo => ARRAY
198              
199             Alternate form of specifying the peer to C to. This should be an
200             array of the form returned by C.
201              
202             This parameter takes precedence over the C, C, C and
203             C arguments.
204              
205             =item LocalHost => STRING
206              
207             =item LocalService => STRING
208              
209             Hostname and service name for the local address to C to.
210              
211             =item LocalAddr => STRING
212              
213             =item LocalPort => STRING
214              
215             For symmetry with the accessor methods and compatibility with
216             C, these are accepted as synonyms for C and
217             C respectively.
218              
219             =item LocalAddrInfo => ARRAY
220              
221             Alternate form of specifying the local address to C to. This should be
222             an array of the form returned by C.
223              
224             This parameter takes precedence over the C, C, C and
225             C arguments.
226              
227             =item Family => INT
228              
229             The address family to pass to C (e.g. C, C).
230             Normally this will be left undefined, and C will search using any
231             address family supported by the system.
232              
233             =item Type => INT
234              
235             The socket type to pass to C (e.g. C,
236             C). Normally defined by the caller; if left undefined
237             C may attempt to infer the type from the service name.
238              
239             =item Proto => STRING or INT
240              
241             The IP protocol to use for the socket (e.g. C<'tcp'>, C,
242             C<'udp'>,C). Normally this will be left undefined, and either
243             C or the kernel will choose an appropriate value. May be given
244             either in string name or numeric form.
245              
246             =item GetAddrInfoFlags => INT
247              
248             More flags to pass to the C function. If not supplied, a
249             default of C will be used.
250              
251             These flags will be combined with C if the C argument is
252             given. For more information see the documentation about C in
253             the L module.
254              
255             =item Listen => INT
256              
257             If defined, puts the socket into listening mode where new connections can be
258             accepted using the C method. The value given is used as the
259             C queue size.
260              
261             =item ReuseAddr => BOOL
262              
263             If true, set the C sockopt
264              
265             =item ReusePort => BOOL
266              
267             If true, set the C sockopt (not all OSes implement this sockopt)
268              
269             =item Broadcast => BOOL
270              
271             If true, set the C sockopt
272              
273             =item Sockopts => ARRAY
274              
275             An optional array of other socket options to apply after the three listed
276             above. The value is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner
277             array relates to a single option, giving the level and option name, and an
278             optional value. If the value element is missing, it will be given the value of
279             a platform-sized integer 1 constant (i.e. suitable to enable most of the
280             common boolean options).
281              
282             For example, both options given below are equivalent to setting C.
283              
284             Sockopts => [
285             [ SOL_SOCKET, SO_REUSEADDR ],
286             [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],
287             ]
288              
289             =item V6Only => BOOL
290              
291             If defined, set the C sockopt when creating C sockets
292             to the given value. If true, a listening-mode socket will only listen on the
293             C addresses; if false it will also accept connections from
294             C addresses.
295              
296             If not defined, the socket option will not be changed, and default value set
297             by the operating system will apply. For repeatable behaviour across platforms
298             it is recommended this value always be defined for listening-mode sockets.
299              
300             Note that not all platforms support disabling this option. Some, at least
301             OpenBSD and MirBSD, will fail with C if you attempt to disable it.
302             To determine whether it is possible to disable, you may use the class method
303              
304             if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
305             ...
306             }
307             else {
308             ...
309             }
310              
311             If your platform does not support disabling this option but you still want to
312             listen for both C and C connections you will have to create
313             two listening sockets, one bound to each protocol.
314              
315             =item MultiHomed
316              
317             This C-style argument is ignored, except if it is defined
318             but false. See the C INCOMPATIBILITIES section below.
319              
320             However, the behaviour it enables is always performed by C.
321              
322             =item Blocking => BOOL
323              
324             If defined but false, the socket will be set to non-blocking mode. Otherwise
325             it will default to blocking mode. See the NON-BLOCKING section below for more
326             detail.
327              
328             =item Timeout => NUM
329              
330             If defined, gives a maximum time in seconds to block per C call
331             when in blocking mode. If missing, no timeout is applied other than that
332             provided by the underlying operating system. When in non-blocking mode this
333             parameter is ignored.
334              
335             Note that if the hostname resolves to multiple address candidates, the same
336             timeout will apply to each connection attempt individually, rather than to the
337             operation as a whole. Further note that the timeout does not apply to the
338             initial hostname resolve operation, if connecting by hostname.
339              
340             This behaviour is copied inspired by C; for more fine
341             grained control over connection timeouts, consider performing a nonblocking
342             connect directly.
343              
344             =back
345              
346             If neither C nor C hints are provided, a default of
347             C and C respectively will be set, to maintain
348             compatibility with C. Other named arguments that are not
349             recognised are ignored.
350              
351             If neither C nor any hosts or addresses are passed, nor any
352             C<*AddrInfo>, then the constructor has no information on which to decide a
353             socket family to create. In this case, it performs a C call with
354             the C flag, no host name, and a service name of C<"0">, and
355             uses the family of the first returned result.
356              
357             If the constructor fails, it will set C<$IO::Socket::errstr> and C<$@> to
358             an appropriate error message; this may be from C<$!> or it may be some other
359             string; not every failure necessarily has an associated C value.
360              
361             =head2 new (one arg)
362              
363             $sock = IO::Socket::IP->new( $peeraddr )
364              
365             As a special case, if the constructor is passed a single argument (as
366             opposed to an even-sized list of key/value pairs), it is taken to be the value
367             of the C parameter. This is parsed in the same way, according to the
368             behaviour given in the C AND C PARSING section below.
369              
370             =cut
371              
372             sub new
373             {
374 61     61 1 4713872 my $class = shift;
375 61 100       506 my %arg = (@_ == 1) ? (PeerHost => $_[0]) : @_;
376 61         463 return $class->SUPER::new(%arg);
377             }
378              
379             # IO::Socket may call this one; neaten up the arguments from IO::Socket::INET
380             # before calling our real _configure method
381             sub configure
382             {
383 55     55 0 5845 my $self = shift;
384 55         172 my ( $arg ) = @_;
385              
386             $arg->{PeerHost} = delete $arg->{PeerAddr}
387 55 50 33     323 if exists $arg->{PeerAddr} && !exists $arg->{PeerHost};
388              
389             $arg->{PeerService} = delete $arg->{PeerPort}
390 55 100 66     269 if exists $arg->{PeerPort} && !exists $arg->{PeerService};
391              
392             $arg->{LocalHost} = delete $arg->{LocalAddr}
393 55 50 33     332 if exists $arg->{LocalAddr} && !exists $arg->{LocalHost};
394              
395             $arg->{LocalService} = delete $arg->{LocalPort}
396 55 100 66     311 if exists $arg->{LocalPort} && !exists $arg->{LocalService};
397              
398 55         179 for my $type (qw(Peer Local)) {
399 110         240 my $host = $type . 'Host';
400 110         212 my $service = $type . 'Service';
401              
402 110 100       398 if( defined $arg->{$host} ) {
403 47         258 ( $arg->{$host}, my $s ) = $self->split_addr( $arg->{$host} );
404             # IO::Socket::INET compat - *Host parsed port always takes precedence
405 47 100       210 $arg->{$service} = $s if defined $s;
406             }
407             }
408              
409 55         244 $self->_io_socket_ip__configure( $arg );
410             }
411              
412             # Avoid simply calling it _configure, as some subclasses of IO::Socket::INET on CPAN already take that
413             sub _io_socket_ip__configure
414             {
415 39     39   90 my $self = shift;
416 39         91 my ( $arg ) = @_;
417              
418 39         126 my %hints;
419             my @localinfos;
420 39         0 my @peerinfos;
421              
422 39         102 my $listenqueue = $arg->{Listen};
423 39 50 33     240 if( defined $listenqueue and
      66        
424             ( defined $arg->{PeerHost} || defined $arg->{PeerService} || defined $arg->{PeerAddrInfo} ) ) {
425 0         0 croak "Cannot Listen with a peer address";
426             }
427              
428 39 100       149 if( defined $arg->{GetAddrInfoFlags} ) {
429 6         18 $hints{flags} = $arg->{GetAddrInfoFlags};
430             }
431             else {
432 33         149 $hints{flags} = $AI_ADDRCONFIG;
433             }
434              
435 39 100       239 if( defined( my $family = $arg->{Family} ) ) {
436 3         7 $hints{family} = $family;
437             }
438              
439 39 100       246 if( defined( my $type = $arg->{Type} ) ) {
440 23         73 $hints{socktype} = $type;
441             }
442              
443 39 50       194 if( defined( my $proto = $arg->{Proto} ) ) {
444 0 0       0 unless( $proto =~ m/^\d+$/ ) {
445             my $protonum = HAVE_GETPROTOBYNAME
446             ? getprotobyname( $proto )
447 0         0 : eval { Socket->${\"IPPROTO_\U$proto"}() };
  0         0  
  0         0  
448 0 0       0 defined $protonum or croak "Unrecognised protocol $proto";
449 0         0 $proto = $protonum;
450             }
451              
452 0         0 $hints{protocol} = $proto;
453             }
454              
455             # To maintain compatibility with IO::Socket::INET, imply a default of
456             # SOCK_STREAM + IPPROTO_TCP if neither hint is given
457 39 50 66     193 if( !defined $hints{socktype} and !defined $hints{protocol} ) {
458 16         43 $hints{socktype} = SOCK_STREAM;
459 16         41 $hints{protocol} = IPPROTO_TCP;
460             }
461              
462             # Some OSes (NetBSD) don't seem to like just a protocol hint without a
463             # socktype hint as well. We'll set a couple of common ones
464 39 50 33     182 if( !defined $hints{socktype} and defined $hints{protocol} ) {
465 0 0       0 $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP;
466 0 0       0 $hints{socktype} = SOCK_DGRAM if $hints{protocol} == IPPROTO_UDP;
467             }
468              
469 39 100 100     444 if( my $info = $arg->{LocalAddrInfo} ) {
    100 100        
470 1 50       6 ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref";
471 1         4 @localinfos = @$info;
472             }
473             elsif( defined $arg->{LocalHost} or
474             defined $arg->{LocalService} or
475             HAVE_MSWIN32 and $arg->{Listen} ) {
476             # Either may be undef
477 23         61 my $host = $arg->{LocalHost};
478 23         72 my $service = $arg->{LocalService};
479              
480 23 50 66     116 unless ( defined $host or defined $service ) {
481 0         0 $service = 0;
482             }
483              
484 23         78 local $1; # Placate a taint-related bug; [perl #67962]
485 23 100 100     159 defined $service and $service =~ s/\((\d+)\)$// and
486             my $fallback_port = $1;
487              
488 23         115 my %localhints = %hints;
489 23         71 $localhints{flags} |= AI_PASSIVE;
490 23         2720 ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints );
491              
492 23 100 100     256 if( $err and defined $fallback_port ) {
493 1         3 ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints );
494             }
495              
496 23 100       152 if( $err ) {
497 5         21 $IO::Socket::errstr = $@ = "$err";
498 5         16 $! = EINVAL;
499 5         176 return;
500             }
501             }
502              
503 34 100 66     283 if( my $info = $arg->{PeerAddrInfo} ) {
    100          
504 1 50       15 ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref";
505 1         4 @peerinfos = @$info;
506             }
507             elsif( defined $arg->{PeerHost} or defined $arg->{PeerService} ) {
508 12 50       45 defined( my $host = $arg->{PeerHost} ) or
509             croak "Expected 'PeerHost'";
510 12 50       55 defined( my $service = $arg->{PeerService} ) or
511             croak "Expected 'PeerService'";
512              
513 12         35 local $1; # Placate a taint-related bug; [perl #67962]
514 12 50 33     117 defined $service and $service =~ s/\((\d+)\)$// and
515             my $fallback_port = $1;
516              
517 12         25939 ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints );
518              
519 12 50 33     87 if( $err and defined $fallback_port ) {
520 0         0 ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints );
521             }
522              
523 12 50       62 if( $err ) {
524 0         0 $IO::Socket::errstr = $@ = "$err";
525 0         0 $! = EINVAL;
526 0         0 return;
527             }
528             }
529              
530 34         104 my $INT_1 = pack "i", 1;
531              
532 34         63 my @sockopts_enabled;
533 34 100       123 push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEADDR, $INT_1 ] if $arg->{ReuseAddr};
534 34 100       119 push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEPORT, $INT_1 ] if $arg->{ReusePort};
535 34 100       124 push @sockopts_enabled, [ SOL_SOCKET, SO_BROADCAST, $INT_1 ] if $arg->{Broadcast};
536              
537 34 100       162 if( my $sockopts = $arg->{Sockopts} ) {
538 1 50       5 ref $sockopts eq "ARRAY" or croak "Expected 'Sockopts' to be an ARRAY ref";
539 1         5 foreach ( @$sockopts ) {
540 1 50       4 ref $_ eq "ARRAY" or croak "Bad Sockopts item - expected ARRAYref";
541 1 50 33     8 @$_ >= 2 and @$_ <= 3 or
542             croak "Bad Sockopts item - expected 2 or 3 elements";
543              
544 1         3 my ( $level, $optname, $value ) = @$_;
545             # TODO: consider more sanity checking on argument values
546              
547 1 50       4 defined $value or $value = $INT_1;
548 1         5 push @sockopts_enabled, [ $level, $optname, $value ];
549             }
550             }
551              
552 34         86 my $blocking = $arg->{Blocking};
553 34 100       137 defined $blocking or $blocking = 1;
554              
555 34         68 my $v6only = $arg->{V6Only};
556              
557             # IO::Socket::INET defines this key. IO::Socket::IP always implements the
558             # behaviour it requests, so we can ignore it, unless the caller is for some
559             # reason asking to disable it.
560 34 50 33     151 if( defined $arg->{MultiHomed} and !$arg->{MultiHomed} ) {
561 0         0 croak "Cannot disable the MultiHomed parameter";
562             }
563              
564 34         76 my @infos;
565 34 100       117 foreach my $local ( @localinfos ? @localinfos : {} ) {
566 34 100       146 foreach my $peer ( @peerinfos ? @peerinfos : {} ) {
567             next if defined $local->{family} and defined $peer->{family} and
568 34 50 66     232 $local->{family} != $peer->{family};
      33        
569             next if defined $local->{socktype} and defined $peer->{socktype} and
570 34 50 66     208 $local->{socktype} != $peer->{socktype};
      33        
571             next if defined $local->{protocol} and defined $peer->{protocol} and
572 34 50 66     183 $local->{protocol} != $peer->{protocol};
      33        
573              
574 34 100 100     199 my $family = $local->{family} || $peer->{family} or next;
575 32 50 66     166 my $socktype = $local->{socktype} || $peer->{socktype} or next;
576 32   50     203 my $protocol = $local->{protocol} || $peer->{protocol} || 0;
577              
578             push @infos, {
579             family => $family,
580             socktype => $socktype,
581             protocol => $protocol,
582             localaddr => $local->{addr},
583             peeraddr => $peer->{addr},
584 32         298 };
585             }
586             }
587              
588 34 100       122 if( !@infos ) {
589             # If there was a Family hint then create a plain unbound, unconnected socket
590 2 100       7 if( defined $hints{family} ) {
591             @infos = ( {
592             family => $hints{family},
593             socktype => $hints{socktype},
594             protocol => $hints{protocol},
595 1         7 } );
596             }
597             # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a
598             # suitable family first.
599             else {
600 1         145 ( my $err, @infos ) = getaddrinfo( "", "0", \%hints );
601 1 50       9 if( $err ) {
602 0         0 $IO::Socket::errstr = $@ = "$err";
603 0         0 $! = EINVAL;
604 0         0 return;
605             }
606              
607             # We'll take all the @infos anyway, because some OSes (HPUX) are known to
608             # ignore the AI_ADDRCONFIG hint and return AF_INET6 even if they don't
609             # support them
610             }
611             }
612              
613             # In the nonblocking case, caller will be calling ->setup multiple times.
614             # Store configuration in the object for the ->setup method
615             # Yes, these are messy. Sorry, I can't help that...
616              
617 34         79 ${*$self}{io_socket_ip_infos} = \@infos;
  34         191  
618              
619 34         80 ${*$self}{io_socket_ip_idx} = -1;
  34         151  
620              
621 34         92 ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled;
  34         179  
622 34         161 ${*$self}{io_socket_ip_v6only} = $v6only;
  34         132  
623 34         66 ${*$self}{io_socket_ip_listenqueue} = $listenqueue;
  34         184  
624 34         88 ${*$self}{io_socket_ip_blocking} = $blocking;
  34         106  
625              
626 34         121 ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ];
  34         119  
627              
628             # ->setup is allowed to return false in nonblocking mode
629 34 50 66     137 $self->setup or !$blocking or return undef;
630              
631 34         590 return $self;
632             }
633              
634             sub setup
635             {
636 35     35 0 75 my $self = shift;
637              
638 35         59 while(1) {
639 35         68 ${*$self}{io_socket_ip_idx}++;
  35         219  
640 35 100       65 last if ${*$self}{io_socket_ip_idx} >= @{ ${*$self}{io_socket_ip_infos} };
  35         98  
  35         83  
  35         207  
641              
642 34         75 my $info = ${*$self}{io_socket_ip_infos}->[${*$self}{io_socket_ip_idx}];
  34         98  
  34         107  
643              
644 34         204 $self->socket( @{$info}{qw( family socktype protocol )} ) or
645 34 50       92 ( ${*$self}{io_socket_ip_errors}[2] = $!, next );
  0         0  
646              
647 34 100       2832 $self->blocking( 0 ) unless ${*$self}{io_socket_ip_blocking};
  34         150  
648              
649 34         128 foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) {
  34         66  
  34         164  
650 4         33 my ( $level, $optname, $value ) = @$sockopt;
651 4 50       21 $self->setsockopt( $level, $optname, $value ) or
652             ( $IO::Socket::errstr = $@ = "$!", return undef );
653             }
654              
655 34 0 33     120 if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info->{family} == $AF_INET6 ) {
  34   33     264  
656 0         0 my $v6only = ${*$self}{io_socket_ip_v6only};
  0         0  
657 0 0       0 $self->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or
658             ( $IO::Socket::errstr = $@ = "$!", return undef );
659             }
660              
661 34 100       151 if( defined( my $addr = $info->{localaddr} ) ) {
662             $self->bind( $addr ) or
663 19 50       171 ( ${*$self}{io_socket_ip_errors}[1] = $!, next );
  0         0  
664             }
665              
666 34 100       1045 if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) {
  34         194  
667 11 50       160 $self->listen( $listenqueue ) or
668             ( $IO::Socket::errstr = $@ = "$!", return undef );
669             }
670              
671 34 100       445 if( defined( my $addr = $info->{peeraddr} ) ) {
672 13 100       73 if( $self->connect( $addr ) ) {
673 10         45 $! = 0;
674 10         45 return 1;
675             }
676              
677 3 50 33     74 if( $! == EINPROGRESS or $! == EWOULDBLOCK ) {
678 3         29 ${*$self}{io_socket_ip_connect_in_progress} = 1;
  3         65  
679 3         29 return 0;
680             }
681              
682             # If connect failed but we have no system error there must be an error
683             # at the application layer, like a bad certificate with
684             # IO::Socket::SSL.
685             # In this case don't continue IP based multi-homing because the problem
686             # cannot be solved at the IP layer.
687 0 0       0 return 0 if ! $!;
688              
689 0         0 ${*$self}{io_socket_ip_errors}[0] = $!;
  0         0  
690 0         0 next;
691             }
692              
693 21         146 return 1;
694             }
695              
696             # Pick the most appropriate error, stringified
697 1         2 $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0];
  1         2  
  1         7  
698 1         7 $IO::Socket::errstr = $@ = "$!";
699 1         82 return undef;
700             }
701              
702             sub connect :method
703             {
704 20     20 0 13557 my $self = shift;
705              
706             # It seems that IO::Socket hides EINPROGRESS errors, making them look like
707             # a success. This is annoying here.
708             # Instead of putting up with its frankly-irritating intentional breakage of
709             # useful APIs I'm just going to end-run around it and call core's connect()
710             # directly
711              
712 20 100       71 if( @_ ) {
713 16         79 my ( $addr ) = @_;
714              
715             # Annoyingly IO::Socket's connect() is where the timeout logic is
716             # implemented, so we'll have to reinvent it here
717 16         37 my $timeout = ${*$self}{'io_socket_timeout'};
  16         70  
718              
719 16 100       1982 return connect( $self, $addr ) unless defined $timeout;
720              
721 1         10 my $was_blocking = $self->blocking( 0 );
722              
723 1 50       140 my $err = defined connect( $self, $addr ) ? 0 : $!+0;
724              
725 1 50 33     8 if( !$err ) {
    50          
    50          
726             # All happy
727 0         0 $self->blocking( $was_blocking );
728 0         0 return 1;
729             }
730             elsif( not( $err == EINPROGRESS or $err == EWOULDBLOCK ) ) {
731             # Failed for some other reason
732 0         0 $self->blocking( $was_blocking );
733 0         0 return undef;
734             }
735             elsif( !$was_blocking ) {
736             # We shouldn't block anyway
737 0         0 return undef;
738             }
739              
740 1         2 my $vec = ''; vec( $vec, $self->fileno, 1 ) = 1;
  1         4  
741 1 50       17 if( !select( undef, $vec, $vec, $timeout ) ) {
742 0         0 $self->blocking( $was_blocking );
743 0         0 $! = ETIMEDOUT;
744 0         0 return undef;
745             }
746              
747             # Hoist the error by connect()ing a second time
748 1         25 $err = $self->getsockopt( SOL_SOCKET, SO_ERROR );
749 1 50       26 $err = 0 if $err == EISCONN; # Some OSes give EISCONN
750              
751 1         14 $self->blocking( $was_blocking );
752              
753 1 50       10 $! = $err, return undef if $err;
754 1         3 return 1;
755             }
756              
757 4 50       6 return 1 if !${*$self}{io_socket_ip_connect_in_progress};
  4         26  
758              
759             # See if a connect attempt has just failed with an error
760 4 100       39 if( my $errno = $self->getsockopt( SOL_SOCKET, SO_ERROR ) ) {
761 1         60 delete ${*$self}{io_socket_ip_connect_in_progress};
  1         6  
762 1         4 ${*$self}{io_socket_ip_errors}[0] = $! = $errno;
  1         9  
763 1         5 return $self->setup;
764             }
765              
766             # No error, so either connect is still in progress, or has completed
767             # successfully. We can tell by trying to connect() again; either it will
768             # succeed or we'll get EISCONN (connected successfully), or EALREADY
769             # (still in progress). This even works on MSWin32.
770 3         78 my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr};
  3         12  
  3         11  
771              
772 3 100 66     38 if( connect( $self, $addr ) or $! == EISCONN ) {
773 2         3 delete ${*$self}{io_socket_ip_connect_in_progress};
  2         6  
774 2         5 $! = 0;
775 2         23 return 1;
776             }
777             else {
778 1         3 $! = EINPROGRESS;
779 1         5 return 0;
780             }
781             }
782              
783             sub connected
784             {
785 11     11 1 37735 my $self = shift;
786             return defined $self->fileno &&
787             !${*$self}{io_socket_ip_connect_in_progress} &&
788 11   66     51 defined getpeername( $self ); # ->peername caches, we need to detect disconnection
789             }
790              
791             =head1 METHODS
792              
793             As well as the following methods, this class inherits all the methods in
794             L and L.
795              
796             =cut
797              
798             sub _get_host_service
799             {
800 65     65   958 my $self = shift;
801 65         178 my ( $addr, $flags, $xflags ) = @_;
802              
803 65 100       274 defined $addr or
804             $! = ENOTCONN, return;
805              
806 57 100       192 $flags |= NI_DGRAM if $self->socktype == SOCK_DGRAM;
807              
808 57   50     1171 my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 );
809 57 50       164 croak "getnameinfo - $err" if $err;
810              
811 57         481 return ( $host, $service );
812             }
813              
814             sub _unpack_sockaddr
815             {
816 14     14   199 my ( $addr ) = @_;
817 14         58 my $family = sockaddr_family $addr;
818              
819 14 100 33     76 if( $family == AF_INET ) {
    50          
820 8         102 return ( Socket::unpack_sockaddr_in( $addr ) )[1];
821             }
822             elsif( defined $AF_INET6 and $family == $AF_INET6 ) {
823 6         116 return ( Socket::unpack_sockaddr_in6( $addr ) )[1];
824             }
825             else {
826 0         0 croak "Unrecognised address family $family";
827             }
828             }
829              
830             =head2 sockhost_service
831              
832             ( $host, $service ) = $sock->sockhost_service( $numeric );
833              
834             Returns the hostname and service name of the local address (that is, the
835             socket address given by the C method).
836              
837             If C<$numeric> is true, these will be given in numeric form rather than being
838             resolved into names.
839              
840             The following four convenience wrappers may be used to obtain one of the two
841             values returned here. If both host and service names are required, this method
842             is preferable to the following wrappers, because it will call
843             C only once.
844              
845             =cut
846              
847             sub sockhost_service
848             {
849 0     0 1 0 my $self = shift;
850 0         0 my ( $numeric ) = @_;
851              
852 0 0       0 $self->_get_host_service( $self->sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
853             }
854              
855             =head2 sockhost
856              
857             $addr = $sock->sockhost;
858              
859             Return the numeric form of the local address as a textual representation
860              
861             =head2 sockport
862              
863             $port = $sock->sockport;
864              
865             Return the numeric form of the local port number
866              
867             =head2 sockhostname
868              
869             $host = $sock->sockhostname;
870              
871             Return the resolved name of the local address
872              
873             =head2 sockservice
874              
875             $service = $sock->sockservice;
876              
877             Return the resolved name of the local port number
878              
879             =cut
880              
881 11     11 1 17953 sub sockhost { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
  11         155  
882 24     24 1 23321 sub sockport { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] }
  24         159  
883              
884 0     0 1 0 sub sockhostname { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOSERV ) )[0] }
  0         0  
885 0     0 1 0 sub sockservice { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOHOST ) )[1] }
  0         0  
886              
887             =head2 sockaddr
888              
889             $addr = $sock->sockaddr;
890              
891             Return the local address as a binary octet string
892              
893             =cut
894              
895 6     6 1 1924 sub sockaddr { my $self = shift; _unpack_sockaddr $self->sockname }
  6         30  
896              
897             =head2 peerhost_service
898              
899             ( $host, $service ) = $sock->peerhost_service( $numeric );
900              
901             Returns the hostname and service name of the peer address (that is, the
902             socket address given by the C method), similar to the
903             C method.
904              
905             The following four convenience wrappers may be used to obtain one of the two
906             values returned here. If both host and service names are required, this method
907             is preferable to the following wrappers, because it will call
908             C only once.
909              
910             =cut
911              
912             sub peerhost_service
913             {
914 0     0 1 0 my $self = shift;
915 0         0 my ( $numeric ) = @_;
916              
917 0 0       0 $self->_get_host_service( $self->peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
918             }
919              
920             =head2 peerhost
921              
922             $addr = $sock->peerhost;
923              
924             Return the numeric form of the peer address as a textual representation
925              
926             =head2 peerport
927              
928             $port = $sock->peerport;
929              
930             Return the numeric form of the peer port number
931              
932             =head2 peerhostname
933              
934             $host = $sock->peerhostname;
935              
936             Return the resolved name of the peer address
937              
938             =head2 peerservice
939              
940             $service = $sock->peerservice;
941              
942             Return the resolved name of the peer port number
943              
944             =cut
945              
946 11     11 1 11105 sub peerhost { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
  11         48  
947 19     19 1 1004 sub peerport { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] }
  19         88  
948              
949 0     0 1 0 sub peerhostname { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOSERV ) )[0] }
  0         0  
950 0     0 1 0 sub peerservice { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOHOST ) )[1] }
  0         0  
951              
952             =head2 peeraddr
953              
954             $addr = $peer->peeraddr;
955              
956             Return the peer address as a binary octet string
957              
958             =cut
959              
960 8     8 1 21 sub peeraddr { my $self = shift; _unpack_sockaddr $self->peername }
  8         35  
961              
962             # This unbelievably dodgy hack works around the bug that IO::Socket doesn't do
963             # it
964             # https://rt.cpan.org/Ticket/Display.html?id=61577
965             sub accept
966             {
967 6     6 1 7397 my $self = shift;
968 6 50       88 my ( $new, $peer ) = $self->SUPER::accept( @_ ) or return;
969              
970 6         999 ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto );
  18         46  
  18         57  
971              
972 6 50       34 return wantarray ? ( $new, $peer )
973             : $new;
974             }
975              
976             # This second unbelievably dodgy hack guarantees that $self->fileno doesn't
977             # change, which is useful during nonblocking connect
978             sub socket :method
979             {
980 37     37 1 8747 my $self = shift;
981 37 100       371 return $self->SUPER::socket(@_) if not defined $self->fileno;
982              
983             # I hate core prototypes sometimes...
984 2 50       77 socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef;
985              
986 2 50       12 dup2( $tmph->fileno, $self->fileno ) or die "Unable to dup2 $tmph onto $self - $!";
987             }
988              
989             # Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an
990             # ->fdopen call. In this case we'll apply a fix
991             BEGIN {
992 22 50   22   1862 if( eval($IO::Socket::VERSION) < 1.35 ) {
993             *socktype = sub {
994 0         0 my $self = shift;
995 0         0 my $type = $self->SUPER::socktype;
996 0 0       0 if( !defined $type ) {
997 0         0 $type = $self->sockopt( Socket::SO_TYPE() );
998             }
999 0         0 return $type;
1000 0         0 };
1001             }
1002             }
1003              
1004             =head2 as_inet
1005              
1006             $inet = $sock->as_inet;
1007              
1008             Returns a new L instance wrapping the same filehandle. This
1009             may be useful in cases where it is required, for backward-compatibility, to
1010             have a real object of C type instead of C.
1011             The new object will wrap the same underlying socket filehandle as the
1012             original, so care should be taken not to continue to use both objects
1013             concurrently. Ideally the original C<$sock> should be discarded after this
1014             method is called.
1015              
1016             This method checks that the socket domain is C and will throw an
1017             exception if it isn't.
1018              
1019             =cut
1020              
1021             sub as_inet
1022             {
1023 1     1 1 7 my $self = shift;
1024 1 50       10 croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self->sockdomain == AF_INET;
1025 1         19 return IO::Socket::INET->new_from_fd( $self->fileno, "r+" );
1026             }
1027              
1028             =head1 NON-BLOCKING
1029              
1030             If the constructor is passed a defined but false value for the C
1031             argument then the socket is put into non-blocking mode. When in non-blocking
1032             mode, the socket will not be set up by the time the constructor returns,
1033             because the underlying C syscall would otherwise have to block.
1034              
1035             The non-blocking behaviour is an extension of the C API,
1036             unique to C, because the former does not support multi-homed
1037             non-blocking connect.
1038              
1039             When using non-blocking mode, the caller must repeatedly check for
1040             writeability on the filehandle (for instance using C
1041             Each time the filehandle is ready to write, the C method must be
1042             called, with no arguments. Note that some operating systems, most notably
1043             C do not report a C failure using write-ready; so you must
1044             also C for exceptional status.
1045              
1046             While C returns false, the value of C<$!> indicates whether it should
1047             be tried again (by being set to the value C, or C on
1048             MSWin32), or whether a permanent error has occurred (e.g. C).
1049              
1050             Once the socket has been connected to the peer, C will return true
1051             and the socket will now be ready to use.
1052              
1053             Note that calls to the platform's underlying C function may
1054             block. If C has to perform this lookup, the constructor will
1055             block even when in non-blocking mode.
1056              
1057             To avoid this blocking behaviour, the caller should pass in the result of such
1058             a lookup using the C or C arguments. This can be
1059             achieved by using L, or the C function can be
1060             called in a child process.
1061              
1062             use IO::Socket::IP;
1063             use Errno qw( EINPROGRESS EWOULDBLOCK );
1064              
1065             my @peeraddrinfo = ... # Caller must obtain the getaddrinfo result here
1066              
1067             my $socket = IO::Socket::IP->new(
1068             PeerAddrInfo => \@peeraddrinfo,
1069             Blocking => 0,
1070             ) or die "Cannot construct socket - $@";
1071              
1072             while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
1073             my $wvec = '';
1074             vec( $wvec, fileno $socket, 1 ) = 1;
1075             my $evec = '';
1076             vec( $evec, fileno $socket, 1 ) = 1;
1077              
1078             select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
1079             }
1080              
1081             die "Cannot connect - $!" if $!;
1082              
1083             ...
1084              
1085             The example above uses C, but any similar mechanism should work
1086             analogously. C takes care when creating new socket filehandles
1087             to preserve the actual file descriptor number, so such techniques as C
1088             or C should be transparent to its reallocation of a different socket
1089             underneath, perhaps in order to switch protocol family between C and
1090             C.
1091              
1092             For another example using C and C, see the
1093             F file in the module distribution.
1094              
1095             =cut
1096              
1097             =head1 C AND C PARSING
1098              
1099             To support the C API, the host and port information may be
1100             passed in a single string rather than as two separate arguments.
1101              
1102             If either C or C (or their C<...Addr> synonyms) have any
1103             of the following special forms then special parsing is applied.
1104              
1105             The value of the C<...Host> argument will be split to give both the hostname
1106             and port (or service name):
1107              
1108             =for highlighter
1109              
1110             hostname.example.org:http # Host name
1111             192.0.2.1:80 # IPv4 address
1112             [2001:db8::1]:80 # IPv6 address
1113              
1114             =for highlighter language=perl
1115              
1116             In each case, the port or service name (e.g. C<80>) is passed as the
1117             C or C argument.
1118              
1119             Either of C or C (or their C<...Port> synonyms) can
1120             be either a service name, a decimal number, or a string containing both a
1121             service name and number, in a form such as
1122              
1123             http(80)
1124              
1125             In this case, the name (C) will be tried first, but if the resolver does
1126             not understand it then the port number (C<80>) will be used instead.
1127              
1128             If the C<...Host> argument is in this special form and the corresponding
1129             C<...Service> or C<...Port> argument is also defined, the one parsed from
1130             the C<...Host> argument will take precedence and the other will be ignored.
1131              
1132             =head2 split_addr
1133              
1134             ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
1135              
1136             Utility method that provides the parsing functionality described above.
1137             Returns a 2-element list, containing either the split hostname and port
1138             description if it could be parsed, or the given address and C if it was
1139             not recognised.
1140              
1141             IO::Socket::IP->split_addr( "hostname:http" );
1142             # ( "hostname", "http" )
1143              
1144             IO::Socket::IP->split_addr( "192.0.2.1:80" );
1145             # ( "192.0.2.1", "80" )
1146              
1147             IO::Socket::IP->split_addr( "[2001:db8::1]:80" );
1148             # ( "2001:db8::1", "80" )
1149              
1150             IO::Socket::IP->split_addr( "something.else" );
1151             # ( "something.else", undef )
1152              
1153             =cut
1154              
1155             sub split_addr
1156             {
1157 51     51 1 267933 shift;
1158 51         133 my ( $addr ) = @_;
1159              
1160 51         450 local ( $1, $2 ); # Placate a taint-related bug; [perl #67962]
1161 51 100 100     18187 if( $addr =~ m/\A\[($IPv6_re)\](?::([^\s:]*))?\z/ or
1162             $addr =~ m/\A([^\s:]*):([^\s:]*)\z/ ) {
1163 17 100 100     212 return ( $1, $2 ) if defined $2 and length $2;
1164 4         24 return ( $1, undef );
1165             }
1166              
1167 34         436 return ( $addr, undef );
1168             }
1169              
1170             =head2 join_addr
1171              
1172             $addr = IO::Socket::IP->join_addr( $host, $port )
1173              
1174             Utility method that performs the reverse of C, returning a string
1175             formed by joining the specified host address and port number. The host address
1176             will be wrapped in C<[]> brackets if required (because it is a raw IPv6
1177             numeric address).
1178              
1179             This can be especially useful when combined with the C or
1180             C methods.
1181              
1182             say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
1183              
1184             =cut
1185              
1186             sub join_addr
1187             {
1188 4     4 1 10 shift;
1189 4         11 my ( $host, $port ) = @_;
1190              
1191 4 100       22 $host = "[$host]" if $host =~ m/:/;
1192              
1193 4 100       27 return join ":", $host, $port if defined $port;
1194 1         6 return $host;
1195             }
1196              
1197             # Since IO::Socket->new( Domain => ... ) will delete the Domain parameter
1198             # before calling ->configure, we need to keep track of which it was
1199              
1200             package # hide from indexer
1201             IO::Socket::IP::_ForINET;
1202 22     22   217 use base qw( IO::Socket::IP );
  22         40  
  22         5954  
1203              
1204             sub configure
1205             {
1206             # This is evil
1207 2     2   279970 my $self = shift;
1208 2         7 my ( $arg ) = @_;
1209              
1210 2         10 bless $self, "IO::Socket::IP";
1211 2         18 $self->configure( { %$arg, Family => Socket::AF_INET() } );
1212             }
1213              
1214             package # hide from indexer
1215             IO::Socket::IP::_ForINET6;
1216 22     22   175 use base qw( IO::Socket::IP );
  22         40  
  22         5766  
1217              
1218             sub configure
1219             {
1220             # This is evil
1221 0     0     my $self = shift;
1222 0           my ( $arg ) = @_;
1223              
1224 0           bless $self, "IO::Socket::IP";
1225 0           $self->configure( { %$arg, Family => Socket::AF_INET6() } );
1226             }
1227              
1228             =head1 C INCOMPATIBILITIES
1229              
1230             =over 4
1231              
1232             =item *
1233              
1234             The behaviour enabled by C is in fact implemented by
1235             C as it is required to correctly support searching for a
1236             useable address from the results of the C call. The
1237             constructor will ignore the value of this argument, except if it is defined
1238             but false. An exception is thrown in this case, because that would request it
1239             disable the C search behaviour in the first place.
1240              
1241             =item *
1242              
1243             C implements both the C and C parameters,
1244             but it implements the interaction of both in a different way.
1245              
1246             In C<::INET>, supplying a timeout overrides the non-blocking behaviour,
1247             meaning that the C operation will still block despite that the
1248             caller asked for a non-blocking socket. This is not explicitly specified in
1249             its documentation, nor does this author believe that is a useful behaviour -
1250             it appears to come from a quirk of implementation.
1251              
1252             In C<::IP> therefore, the C parameter takes precedence - if a
1253             non-blocking socket is requested, no operation will block. The C
1254             parameter here simply defines the maximum time that a blocking C
1255             call will wait, if it blocks at all.
1256              
1257             In order to specifically obtain the "blocking connect then non-blocking send
1258             and receive" behaviour of specifying this combination of options to C<::INET>
1259             when using C<::IP>, perform first a blocking connect, then afterwards turn the
1260             socket into nonblocking mode.
1261              
1262             my $sock = IO::Socket::IP->new(
1263             PeerHost => $peer,
1264             Timeout => 20,
1265             ) or die "Cannot connect - $@";
1266              
1267             $sock->blocking( 0 );
1268              
1269             This code will behave identically under both C and
1270             C.
1271              
1272             =back
1273              
1274             =cut
1275              
1276             =head1 TODO
1277              
1278             =over 4
1279              
1280             =item *
1281              
1282             Investigate whether C upsets BSD's C watchers, and if so,
1283             consider what possible workarounds might be applied.
1284              
1285             =back
1286              
1287             =head1 AUTHOR
1288              
1289             Paul Evans
1290              
1291             =cut
1292              
1293             0x55AA;