<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#  You may distribute under the terms of either the GNU General Public License
#  or the Artistic License (the same terms as Perl itself)
#
#  (C) Paul Evans, 2010-2015 -- leonerd@leonerd.org.uk

package IO::Socket::IP;
# $VERSION needs to be set before  use base 'IO::Socket'
#  - https://rt.cpan.org/Ticket/Display.html?id=92107
BEGIN {
   $VERSION = '0.39';
}

use strict;
use warnings;
use base qw( IO::Socket );

use Carp;

use Socket 1.97 qw(
   getaddrinfo getnameinfo
   sockaddr_family
   AF_INET
   AI_PASSIVE
   IPPROTO_TCP IPPROTO_UDP
   IPPROTO_IPV6 IPV6_V6ONLY
   NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV
   SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR
   SOCK_DGRAM SOCK_STREAM
   SOL_SOCKET
);
my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined
my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0;
use POSIX qw( dup2 );
use Errno qw( EINVAL EINPROGRESS EISCONN ENOTCONN ETIMEDOUT EWOULDBLOCK EOPNOTSUPP );

use constant HAVE_MSWIN32 =&gt; ( $^O eq "MSWin32" );

# At least one OS (Android) is known not to have getprotobyname()
use constant HAVE_GETPROTOBYNAME =&gt; defined eval { getprotobyname( "tcp" ) };

my $IPv6_re = do {
   # translation of RFC 3986 3.2.2 ABNF to re
   my $IPv4address = do {
      my $dec_octet = q&lt;(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])&gt;;
      qq&lt;$dec_octet(?: \\. $dec_octet){3}&gt;;
   };
   my $IPv6address = do {
      my $h16  = qq&lt;[0-9A-Fa-f]{1,4}&gt;;
      my $ls32 = qq&lt;(?: $h16 : $h16 | $IPv4address)&gt;;
      qq&lt;(?:
                                            (?: $h16 : ){6} $ls32
         |                               :: (?: $h16 : ){5} $ls32
         | (?:                   $h16 )? :: (?: $h16 : ){4} $ls32
         | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32
         | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32
         | (?: (?: $h16 : ){0,3} $h16 )? ::     $h16 :      $ls32
         | (?: (?: $h16 : ){0,4} $h16 )? ::                 $ls32
         | (?: (?: $h16 : ){0,5} $h16 )? ::                 $h16
         | (?: (?: $h16 : ){0,6} $h16 )? ::
      )&gt;
   };
   qr&lt;$IPv6address&gt;xo;
};

=head1 NAME

C&lt;IO::Socket::IP&gt; - Family-neutral IP socket supporting both IPv4 and IPv6

=head1 SYNOPSIS

 use IO::Socket::IP;

 my $sock = IO::Socket::IP-&gt;new(
    PeerHost =&gt; "www.google.com",
    PeerPort =&gt; "http",
    Type     =&gt; SOCK_STREAM,
 ) or die "Cannot construct socket - $@";

 my $familyname = ( $sock-&gt;sockdomain == PF_INET6 ) ? "IPv6" :
                  ( $sock-&gt;sockdomain == PF_INET  ) ? "IPv4" :
                                                      "unknown";

 printf "Connected to google via %s\n", $familyname;

=head1 DESCRIPTION

This module provides a protocol-independent way to use IPv4 and IPv6 sockets,
intended as a replacement for L&lt;IO::Socket::INET&gt;. Most constructor arguments
and methods are provided in a backward-compatible way. For a list of known
differences, see the C&lt;IO::Socket::INET&gt; INCOMPATIBILITES section below.

It uses the C&lt;getaddrinfo(3)&gt; function to convert hostnames and service names
or port numbers into sets of possible addresses to connect to or listen on.
This allows it to work for IPv6 where the system supports it, while still
falling back to IPv4-only on systems which don't.

=head1 REPLACING C&lt;IO::Socket&gt; DEFAULT BEHAVIOUR

By placing C&lt;-register&gt; in the import list, L&lt;IO::Socket&gt; uses
C&lt;IO::Socket::IP&gt; rather than C&lt;IO::Socket::INET&gt; as the class that handles
C&lt;PF_INET&gt;.  C&lt;IO::Socket&gt; will also use C&lt;IO::Socket::IP&gt; rather than
C&lt;IO::Socket::INET6&gt; to handle C&lt;PF_INET6&gt;, provided that the C&lt;AF_INET6&gt;
constant is available.

Changing C&lt;IO::Socket&gt;'s default behaviour means that calling the
C&lt;IO::Socket&gt; constructor with either C&lt;PF_INET&gt; or C&lt;PF_INET6&gt; as the
C&lt;Domain&gt; parameter will yield an C&lt;IO::Socket::IP&gt; object.

 use IO::Socket::IP -register;

 my $sock = IO::Socket-&gt;new(
    Domain    =&gt; PF_INET6,
    LocalHost =&gt; "::1",
    Listen    =&gt; 1,
 ) or die "Cannot create socket - $@\n";

 print "Created a socket of type " . ref($sock) . "\n";

Note that C&lt;-register&gt; is a global setting that applies to the entire program;
it cannot be applied only for certain callers, removed, or limited by lexical
scope.

=cut

sub import
{
   my $pkg = shift;
   my @symbols;

   foreach ( @_ ) {
      if( $_ eq "-register" ) {
         IO::Socket::IP::_ForINET-&gt;register_domain( AF_INET );
         IO::Socket::IP::_ForINET6-&gt;register_domain( $AF_INET6 ) if defined $AF_INET6;
      }
      else {
         push @symbols, $_;
      }
   }

   @_ = ( $pkg, @symbols );
   goto &amp;IO::Socket::import;
}

# Convenient capability test function
{
   my $can_disable_v6only;
   sub CAN_DISABLE_V6ONLY
   {
      return $can_disable_v6only if defined $can_disable_v6only;

      socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or
         die "Cannot socket(PF_INET6) - $!";

      if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) {
         return $can_disable_v6only = 1;
      }
      elsif( $! == EINVAL || $! == EOPNOTSUPP ) {
         return $can_disable_v6only = 0;
      }
      else {
         die "Cannot setsockopt() - $!";
      }
   }
}

=head1 CONSTRUCTORS

=cut

=head2 $sock = IO::Socket::IP-&gt;new( %args )

Creates a new C&lt;IO::Socket::IP&gt; object, containing a newly created socket
handle according to the named arguments passed. The recognised arguments are:

=over 8

=item PeerHost =&gt; STRING

=item PeerService =&gt; STRING

Hostname and service name for the peer to C&lt;connect()&gt; to. The service name
may be given as a port number, as a decimal string.

=item PeerAddr =&gt; STRING

=item PeerPort =&gt; STRING

For symmetry with the accessor methods and compatibility with
C&lt;IO::Socket::INET&gt;, these are accepted as synonyms for C&lt;PeerHost&gt; and
C&lt;PeerService&gt; respectively.

=item PeerAddrInfo =&gt; ARRAY

Alternate form of specifying the peer to C&lt;connect()&gt; to. This should be an
array of the form returned by C&lt;Socket::getaddrinfo&gt;.

This parameter takes precedence over the C&lt;Peer*&gt;, C&lt;Family&gt;, C&lt;Type&gt; and
C&lt;Proto&gt; arguments.

=item LocalHost =&gt; STRING

=item LocalService =&gt; STRING

Hostname and service name for the local address to C&lt;bind()&gt; to.

=item LocalAddr =&gt; STRING

=item LocalPort =&gt; STRING

For symmetry with the accessor methods and compatibility with
C&lt;IO::Socket::INET&gt;, these are accepted as synonyms for C&lt;LocalHost&gt; and
C&lt;LocalService&gt; respectively.

=item LocalAddrInfo =&gt; ARRAY

Alternate form of specifying the local address to C&lt;bind()&gt; to. This should be
an array of the form returned by C&lt;Socket::getaddrinfo&gt;.

This parameter takes precedence over the C&lt;Local*&gt;, C&lt;Family&gt;, C&lt;Type&gt; and
C&lt;Proto&gt; arguments.

=item Family =&gt; INT

The address family to pass to C&lt;getaddrinfo&gt; (e.g. C&lt;AF_INET&gt;, C&lt;AF_INET6&gt;).
Normally this will be left undefined, and C&lt;getaddrinfo&gt; will search using any
address family supported by the system.

=item Type =&gt; INT

The socket type to pass to C&lt;getaddrinfo&gt; (e.g. C&lt;SOCK_STREAM&gt;,
C&lt;SOCK_DGRAM&gt;). Normally defined by the caller; if left undefined
C&lt;getaddrinfo&gt; may attempt to infer the type from the service name.

=item Proto =&gt; STRING or INT

The IP protocol to use for the socket (e.g. C&lt;'tcp'&gt;, C&lt;IPPROTO_TCP&gt;,
C&lt;'udp'&gt;,C&lt;IPPROTO_UDP&gt;). Normally this will be left undefined, and either
C&lt;getaddrinfo&gt; or the kernel will choose an appropriate value. May be given
either in string name or numeric form.

=item GetAddrInfoFlags =&gt; INT

More flags to pass to the C&lt;getaddrinfo()&gt; function. If not supplied, a
default of C&lt;AI_ADDRCONFIG&gt; will be used.

These flags will be combined with C&lt;AI_PASSIVE&gt; if the C&lt;Listen&gt; argument is
given. For more information see the documentation about C&lt;getaddrinfo()&gt; in
the L&lt;Socket&gt; module.

=item Listen =&gt; INT

If defined, puts the socket into listening mode where new connections can be
accepted using the C&lt;accept&gt; method. The value given is used as the
C&lt;listen(2)&gt; queue size.

=item ReuseAddr =&gt; BOOL

If true, set the C&lt;SO_REUSEADDR&gt; sockopt

=item ReusePort =&gt; BOOL

If true, set the C&lt;SO_REUSEPORT&gt; sockopt (not all OSes implement this sockopt)

=item Broadcast =&gt; BOOL

If true, set the C&lt;SO_BROADCAST&gt; sockopt

=item Sockopts =&gt; ARRAY

An optional array of other socket options to apply after the three listed
above. The value is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner
array relates to a single option, giving the level and option name, and an
optional value. If the value element is missing, it will be given the value of
a platform-sized integer 1 constant (i.e. suitable to enable most of the
common boolean options).

For example, both options given below are equivalent to setting C&lt;ReuseAddr&gt;.

 Sockopts =&gt; [
    [ SOL_SOCKET, SO_REUSEADDR ],
    [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],
 ]

=item V6Only =&gt; BOOL

If defined, set the C&lt;IPV6_V6ONLY&gt; sockopt when creating C&lt;PF_INET6&gt; sockets
to the given value. If true, a listening-mode socket will only listen on the
C&lt;AF_INET6&gt; addresses; if false it will also accept connections from
C&lt;AF_INET&gt; addresses.

If not defined, the socket option will not be changed, and default value set
by the operating system will apply. For repeatable behaviour across platforms
it is recommended this value always be defined for listening-mode sockets.

Note that not all platforms support disabling this option. Some, at least
OpenBSD and MirBSD, will fail with C&lt;EINVAL&gt; if you attempt to disable it.
To determine whether it is possible to disable, you may use the class method

 if( IO::Socket::IP-&gt;CAN_DISABLE_V6ONLY ) {
    ...
 }
 else {
    ...
 }

If your platform does not support disabling this option but you still want to
listen for both C&lt;AF_INET&gt; and C&lt;AF_INET6&gt; connections you will have to create
two listening sockets, one bound to each protocol.

=item MultiHomed

This C&lt;IO::Socket::INET&gt;-style argument is ignored, except if it is defined
but false. See the C&lt;IO::Socket::INET&gt; INCOMPATIBILITES section below.

However, the behaviour it enables is always performed by C&lt;IO::Socket::IP&gt;.

=item Blocking =&gt; BOOL

If defined but false, the socket will be set to non-blocking mode. Otherwise
it will default to blocking mode. See the NON-BLOCKING section below for more
detail.

=item Timeout =&gt; NUM

If defined, gives a maximum time in seconds to block per C&lt;connect()&gt; call
when in blocking mode. If missing, no timeout is applied other than that
provided by the underlying operating system. When in non-blocking mode this
parameter is ignored.

Note that if the hostname resolves to multiple address candidates, the same
timeout will apply to each connection attempt individually, rather than to the
operation as a whole. Further note that the timeout does not apply to the
initial hostname resolve operation, if connecting by hostname.

This behviour is copied inspired by C&lt;IO::Socket::INET&gt;; for more fine grained
control over connection timeouts, consider performing a nonblocking connect
directly.

=back

If neither C&lt;Type&gt; nor C&lt;Proto&gt; hints are provided, a default of
C&lt;SOCK_STREAM&gt; and C&lt;IPPROTO_TCP&gt; respectively will be set, to maintain
compatibility with C&lt;IO::Socket::INET&gt;. Other named arguments that are not
recognised are ignored.

If neither C&lt;Family&gt; nor any hosts or addresses are passed, nor any
C&lt;*AddrInfo&gt;, then the constructor has no information on which to decide a
socket family to create. In this case, it performs a C&lt;getaddinfo&gt; call with
the C&lt;AI_ADDRCONFIG&gt; flag, no host name, and a service name of C&lt;"0"&gt;, and
uses the family of the first returned result.

If the constructor fails, it will set C&lt;$@&gt; to an appropriate error message;
this may be from C&lt;$!&gt; or it may be some other string; not every failure
necessarily has an associated C&lt;errno&gt; value.

=head2 $sock = IO::Socket::IP-&gt;new( $peeraddr )

As a special case, if the constructor is passed a single argument (as
opposed to an even-sized list of key/value pairs), it is taken to be the value
of the C&lt;PeerAddr&gt; parameter. This is parsed in the same way, according to the
behaviour given in the C&lt;PeerHost&gt; AND C&lt;LocalHost&gt; PARSING section below.

=cut

sub new
{
   my $class = shift;
   my %arg = (@_ == 1) ? (PeerHost =&gt; $_[0]) : @_;
   return $class-&gt;SUPER::new(%arg);
}

# IO::Socket may call this one; neaten up the arguments from IO::Socket::INET
# before calling our real _configure method
sub configure
{
   my $self = shift;
   my ( $arg ) = @_;

   $arg-&gt;{PeerHost} = delete $arg-&gt;{PeerAddr}
      if exists $arg-&gt;{PeerAddr} &amp;&amp; !exists $arg-&gt;{PeerHost};

   $arg-&gt;{PeerService} = delete $arg-&gt;{PeerPort}
      if exists $arg-&gt;{PeerPort} &amp;&amp; !exists $arg-&gt;{PeerService};

   $arg-&gt;{LocalHost} = delete $arg-&gt;{LocalAddr}
      if exists $arg-&gt;{LocalAddr} &amp;&amp; !exists $arg-&gt;{LocalHost};

   $arg-&gt;{LocalService} = delete $arg-&gt;{LocalPort}
      if exists $arg-&gt;{LocalPort} &amp;&amp; !exists $arg-&gt;{LocalService};

   for my $type (qw(Peer Local)) {
      my $host    = $type . 'Host';
      my $service = $type . 'Service';

      if( defined $arg-&gt;{$host} ) {
         ( $arg-&gt;{$host}, my $s ) = $self-&gt;split_addr( $arg-&gt;{$host} );
         # IO::Socket::INET compat - *Host parsed port always takes precedence
         $arg-&gt;{$service} = $s if defined $s;
      }
   }

   $self-&gt;_io_socket_ip__configure( $arg );
}

# Avoid simply calling it _configure, as some subclasses of IO::Socket::INET on CPAN already take that
sub _io_socket_ip__configure
{
   my $self = shift;
   my ( $arg ) = @_;

   my %hints;
   my @localinfos;
   my @peerinfos;

   my $listenqueue = $arg-&gt;{Listen};
   if( defined $listenqueue and
       ( defined $arg-&gt;{PeerHost} || defined $arg-&gt;{PeerService} || defined $arg-&gt;{PeerAddrInfo} ) ) {
      croak "Cannot Listen with a peer address";
   }

   if( defined $arg-&gt;{GetAddrInfoFlags} ) {
      $hints{flags} = $arg-&gt;{GetAddrInfoFlags};
   }
   else {
      $hints{flags} = $AI_ADDRCONFIG;
   }

   if( defined( my $family = $arg-&gt;{Family} ) ) {
      $hints{family} = $family;
   }

   if( defined( my $type = $arg-&gt;{Type} ) ) {
      $hints{socktype} = $type;
   }

   if( defined( my $proto = $arg-&gt;{Proto} ) ) {
      unless( $proto =~ m/^\d+$/ ) {
         my $protonum = HAVE_GETPROTOBYNAME
            ? getprotobyname( $proto )
            : eval { Socket-&gt;${\"IPPROTO_\U$proto"}() };
         defined $protonum or croak "Unrecognised protocol $proto";
         $proto = $protonum;
      }

      $hints{protocol} = $proto;
   }

   # To maintain compatibility with IO::Socket::INET, imply a default of
   # SOCK_STREAM + IPPROTO_TCP if neither hint is given
   if( !defined $hints{socktype} and !defined $hints{protocol} ) {
      $hints{socktype} = SOCK_STREAM;
      $hints{protocol} = IPPROTO_TCP;
   }

   # Some OSes (NetBSD) don't seem to like just a protocol hint without a
   # socktype hint as well. We'll set a couple of common ones
   if( !defined $hints{socktype} and defined $hints{protocol} ) {
      $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP;
      $hints{socktype} = SOCK_DGRAM  if $hints{protocol} == IPPROTO_UDP;
   }

   if( my $info = $arg-&gt;{LocalAddrInfo} ) {
      ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref";
      @localinfos = @$info;
   }
   elsif( defined $arg-&gt;{LocalHost} or
          defined $arg-&gt;{LocalService} or
          HAVE_MSWIN32 and $arg-&gt;{Listen} ) {
      # Either may be undef
      my $host = $arg-&gt;{LocalHost};
      my $service = $arg-&gt;{LocalService};

      unless ( defined $host or defined $service ) {
         $service = 0;
      }

      local $1; # Placate a taint-related bug; [perl #67962]
      defined $service and $service =~ s/\((\d+)\)$// and
         my $fallback_port = $1;

      my %localhints = %hints;
      $localhints{flags} |= AI_PASSIVE;
      ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints );

      if( $err and defined $fallback_port ) {
         ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints );
      }

      if( $err ) {
         $@ = "$err";
         $! = EINVAL;
         return;
      }
   }

   if( my $info = $arg-&gt;{PeerAddrInfo} ) {
      ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref";
      @peerinfos = @$info;
   }
   elsif( defined $arg-&gt;{PeerHost} or defined $arg-&gt;{PeerService} ) {
      defined( my $host = $arg-&gt;{PeerHost} ) or
         croak "Expected 'PeerHost'";
      defined( my $service = $arg-&gt;{PeerService} ) or
         croak "Expected 'PeerService'";

      local $1; # Placate a taint-related bug; [perl #67962]
      defined $service and $service =~ s/\((\d+)\)$// and
         my $fallback_port = $1;

      ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints );

      if( $err and defined $fallback_port ) {
         ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints );
      }

      if( $err ) {
         $@ = "$err";
         $! = EINVAL;
         return;
      }
   }

   my $INT_1 = pack "i", 1;

   my @sockopts_enabled;
   push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEADDR, $INT_1 ] if $arg-&gt;{ReuseAddr};
   push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEPORT, $INT_1 ] if $arg-&gt;{ReusePort};
   push @sockopts_enabled, [ SOL_SOCKET, SO_BROADCAST, $INT_1 ] if $arg-&gt;{Broadcast};

   if( my $sockopts = $arg-&gt;{Sockopts} ) {
      ref $sockopts eq "ARRAY" or croak "Expected 'Sockopts' to be an ARRAY ref";
      foreach ( @$sockopts ) {
         ref $_ eq "ARRAY" or croak "Bad Sockopts item - expected ARRAYref";
         @$_ &gt;= 2 and @$_ &lt;= 3 or
            croak "Bad Sockopts item - expected 2 or 3 elements";

         my ( $level, $optname, $value ) = @$_;
         # TODO: consider more sanity checking on argument values

         defined $value or $value = $INT_1;
         push @sockopts_enabled, [ $level, $optname, $value ];
      }
   }

   my $blocking = $arg-&gt;{Blocking};
   defined $blocking or $blocking = 1;

   my $v6only = $arg-&gt;{V6Only};

   # IO::Socket::INET defines this key. IO::Socket::IP always implements the
   # behaviour it requests, so we can ignore it, unless the caller is for some
   # reason asking to disable it.
   if( defined $arg-&gt;{MultiHomed} and !$arg-&gt;{MultiHomed} ) {
      croak "Cannot disable the MultiHomed parameter";
   }

   my @infos;
   foreach my $local ( @localinfos ? @localinfos : {} ) {
      foreach my $peer ( @peerinfos ? @peerinfos : {} ) {
         next if defined $local-&gt;{family}   and defined $peer-&gt;{family}   and
            $local-&gt;{family} != $peer-&gt;{family};
         next if defined $local-&gt;{socktype} and defined $peer-&gt;{socktype} and
            $local-&gt;{socktype} != $peer-&gt;{socktype};
         next if defined $local-&gt;{protocol} and defined $peer-&gt;{protocol} and
            $local-&gt;{protocol} != $peer-&gt;{protocol};

         my $family   = $local-&gt;{family}   || $peer-&gt;{family}   or next;
         my $socktype = $local-&gt;{socktype} || $peer-&gt;{socktype} or next;
         my $protocol = $local-&gt;{protocol} || $peer-&gt;{protocol} || 0;

         push @infos, {
            family    =&gt; $family,
            socktype  =&gt; $socktype,
            protocol  =&gt; $protocol,
            localaddr =&gt; $local-&gt;{addr},
            peeraddr  =&gt; $peer-&gt;{addr},
         };
      }
   }

   if( !@infos ) {
      # If there was a Family hint then create a plain unbound, unconnected socket
      if( defined $hints{family} ) {
         @infos = ( {
            family   =&gt; $hints{family},
            socktype =&gt; $hints{socktype},
            protocol =&gt; $hints{protocol},
         } );
      }
      # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a
      # suitable family first.
      else {
         ( my $err, @infos ) = getaddrinfo( "", "0", \%hints );
         if( $err ) {
            $@ = "$err";
            $! = EINVAL;
            return;
         }

         # We'll take all the @infos anyway, because some OSes (HPUX) are known to
         # ignore the AI_ADDRCONFIG hint and return AF_INET6 even if they don't
         # support them
      }
   }

   # In the nonblocking case, caller will be calling -&gt;setup multiple times.
   # Store configuration in the object for the -&gt;setup method
   # Yes, these are messy. Sorry, I can't help that...

   ${*$self}{io_socket_ip_infos} = \@infos;

   ${*$self}{io_socket_ip_idx} = -1;

   ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled;
   ${*$self}{io_socket_ip_v6only} = $v6only;
   ${*$self}{io_socket_ip_listenqueue} = $listenqueue;
   ${*$self}{io_socket_ip_blocking} = $blocking;

   ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ];

   # -&gt;setup is allowed to return false in nonblocking mode
   $self-&gt;setup or !$blocking or return undef;

   return $self;
}

sub setup
{
   my $self = shift;

   while(1) {
      ${*$self}{io_socket_ip_idx}++;
      last if ${*$self}{io_socket_ip_idx} &gt;= @{ ${*$self}{io_socket_ip_infos} };

      my $info = ${*$self}{io_socket_ip_infos}-&gt;[${*$self}{io_socket_ip_idx}];

      $self-&gt;socket( @{$info}{qw( family socktype protocol )} ) or
         ( ${*$self}{io_socket_ip_errors}[2] = $!, next );

      $self-&gt;blocking( 0 ) unless ${*$self}{io_socket_ip_blocking};

      foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) {
         my ( $level, $optname, $value ) = @$sockopt;
         $self-&gt;setsockopt( $level, $optname, $value ) or ( $@ = "$!", return undef );
      }

      if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info-&gt;{family} == $AF_INET6 ) {
         my $v6only = ${*$self}{io_socket_ip_v6only};
         $self-&gt;setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or ( $@ = "$!", return undef );
      }

      if( defined( my $addr = $info-&gt;{localaddr} ) ) {
         $self-&gt;bind( $addr ) or
            ( ${*$self}{io_socket_ip_errors}[1] = $!, next );
      }

      if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) {
         $self-&gt;listen( $listenqueue ) or ( $@ = "$!", return undef );
      }

      if( defined( my $addr = $info-&gt;{peeraddr} ) ) {
         if( $self-&gt;connect( $addr ) ) {
            $! = 0;
            return 1;
         }

         if( $! == EINPROGRESS or $! == EWOULDBLOCK ) {
            ${*$self}{io_socket_ip_connect_in_progress} = 1;
            return 0;
         }

         # If connect failed but we have no system error there must be an error
         # at the application layer, like a bad certificate with
         # IO::Socket::SSL.
         # In this case don't continue IP based multi-homing because the problem
         # cannot be solved at the IP layer.
         return 0 if ! $!;

         ${*$self}{io_socket_ip_errors}[0] = $!;
         next;
      }

      return 1;
   }

   # Pick the most appropriate error, stringified
   $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0];
   $@ = "$!";
   return undef;
}

sub connect :method
{
   my $self = shift;

   # It seems that IO::Socket hides EINPROGRESS errors, making them look like
   # a success. This is annoying here.
   # Instead of putting up with its frankly-irritating intentional breakage of
   # useful APIs I'm just going to end-run around it and call core's connect()
   # directly

   if( @_ ) {
      my ( $addr ) = @_;

      # Annoyingly IO::Socket's connect() is where the timeout logic is
      # implemented, so we'll have to reinvent it here
      my $timeout = ${*$self}{'io_socket_timeout'};

      return connect( $self, $addr ) unless defined $timeout;

      my $was_blocking = $self-&gt;blocking( 0 );

      my $err = defined connect( $self, $addr ) ? 0 : $!+0;

      if( !$err ) {
         # All happy
         $self-&gt;blocking( $was_blocking );
         return 1;
      }
      elsif( not( $err == EINPROGRESS or $err == EWOULDBLOCK ) ) {
         # Failed for some other reason
         $self-&gt;blocking( $was_blocking );
         return undef;
      }
      elsif( !$was_blocking ) {
         # We shouldn't block anyway
         return undef;
      }

      my $vec = ''; vec( $vec, $self-&gt;fileno, 1 ) = 1;
      if( !select( undef, $vec, $vec, $timeout ) ) {
         $self-&gt;blocking( $was_blocking );
         $! = ETIMEDOUT;
         return undef;
      }

      # Hoist the error by connect()ing a second time
      $err = $self-&gt;getsockopt( SOL_SOCKET, SO_ERROR );
      $err = 0 if $err == EISCONN; # Some OSes give EISCONN

      $self-&gt;blocking( $was_blocking );

      $! = $err, return undef if $err;
      return 1;
   }

   return 1 if !${*$self}{io_socket_ip_connect_in_progress};

   # See if a connect attempt has just failed with an error
   if( my $errno = $self-&gt;getsockopt( SOL_SOCKET, SO_ERROR ) ) {
      delete ${*$self}{io_socket_ip_connect_in_progress};
      ${*$self}{io_socket_ip_errors}[0] = $! = $errno;
      return $self-&gt;setup;
   }

   # No error, so either connect is still in progress, or has completed
   # successfully. We can tell by trying to connect() again; either it will
   # succeed or we'll get EISCONN (connected successfully), or EALREADY
   # (still in progress). This even works on MSWin32.
   my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr};

   if( connect( $self, $addr ) or $! == EISCONN ) {
      delete ${*$self}{io_socket_ip_connect_in_progress};
      $! = 0;
      return 1;
   }
   else {
      $! = EINPROGRESS;
      return 0;
   }
}

sub connected
{
   my $self = shift;
   return defined $self-&gt;fileno &amp;&amp;
          !${*$self}{io_socket_ip_connect_in_progress} &amp;&amp;
          defined getpeername( $self ); # -&gt;peername caches, we need to detect disconnection
}

=head1 METHODS

As well as the following methods, this class inherits all the methods in
L&lt;IO::Socket&gt; and L&lt;IO::Handle&gt;.

=cut

sub _get_host_service
{
   my $self = shift;
   my ( $addr, $flags, $xflags ) = @_;

   defined $addr or
      $! = ENOTCONN, return;

   $flags |= NI_DGRAM if $self-&gt;socktype == SOCK_DGRAM;

   my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 );
   croak "getnameinfo - $err" if $err;

   return ( $host, $service );
}

sub _unpack_sockaddr
{
   my ( $addr ) = @_;
   my $family = sockaddr_family $addr;

   if( $family == AF_INET ) {
      return ( Socket::unpack_sockaddr_in( $addr ) )[1];
   }
   elsif( defined $AF_INET6 and $family == $AF_INET6 ) {
      return ( Socket::unpack_sockaddr_in6( $addr ) )[1];
   }
   else {
      croak "Unrecognised address family $family";
   }
}

=head2 ( $host, $service ) = $sock-&gt;sockhost_service( $numeric )

Returns the hostname and service name of the local address (that is, the
socket address given by the C&lt;sockname&gt; method).

If C&lt;$numeric&gt; is true, these will be given in numeric form rather than being
resolved into names.

The following four convenience wrappers may be used to obtain one of the two
values returned here. If both host and service names are required, this method
is preferable to the following wrappers, because it will call
C&lt;getnameinfo(3)&gt; only once.

=cut

sub sockhost_service
{
   my $self = shift;
   my ( $numeric ) = @_;

   $self-&gt;_get_host_service( $self-&gt;sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
}

=head2 $addr = $sock-&gt;sockhost

Return the numeric form of the local address as a textual representation

=head2 $port = $sock-&gt;sockport

Return the numeric form of the local port number

=head2 $host = $sock-&gt;sockhostname

Return the resolved name of the local address

=head2 $service = $sock-&gt;sockservice

Return the resolved name of the local port number

=cut

sub sockhost { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
sub sockport { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] }

sub sockhostname { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;sockname, 0, NIx_NOSERV ) )[0] }
sub sockservice  { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;sockname, 0, NIx_NOHOST ) )[1] }

=head2 $addr = $sock-&gt;sockaddr

Return the local address as a binary octet string

=cut

sub sockaddr { my $self = shift; _unpack_sockaddr $self-&gt;sockname }

=head2 ( $host, $service ) = $sock-&gt;peerhost_service( $numeric )

Returns the hostname and service name of the peer address (that is, the
socket address given by the C&lt;peername&gt; method), similar to the
C&lt;sockhost_service&gt; method.

The following four convenience wrappers may be used to obtain one of the two
values returned here. If both host and service names are required, this method
is preferable to the following wrappers, because it will call
C&lt;getnameinfo(3)&gt; only once.

=cut

sub peerhost_service
{
   my $self = shift;
   my ( $numeric ) = @_;

   $self-&gt;_get_host_service( $self-&gt;peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
}

=head2 $addr = $sock-&gt;peerhost

Return the numeric form of the peer address as a textual representation

=head2 $port = $sock-&gt;peerport

Return the numeric form of the peer port number

=head2 $host = $sock-&gt;peerhostname

Return the resolved name of the peer address

=head2 $service = $sock-&gt;peerservice

Return the resolved name of the peer port number

=cut

sub peerhost { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
sub peerport { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] }

sub peerhostname { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;peername, 0, NIx_NOSERV ) )[0] }
sub peerservice  { my $self = shift; scalar +( $self-&gt;_get_host_service( $self-&gt;peername, 0, NIx_NOHOST ) )[1] }

=head2 $addr = $peer-&gt;peeraddr

Return the peer address as a binary octet string

=cut

sub peeraddr { my $self = shift; _unpack_sockaddr $self-&gt;peername }

# This unbelievably dodgy hack works around the bug that IO::Socket doesn't do
# it
#    https://rt.cpan.org/Ticket/Display.html?id=61577
sub accept
{
   my $self = shift;
   my ( $new, $peer ) = $self-&gt;SUPER::accept( @_ ) or return;

   ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto );

   return wantarray ? ( $new, $peer )
                    : $new;
}

# This second unbelievably dodgy hack guarantees that $self-&gt;fileno doesn't
# change, which is useful during nonblocking connect
sub socket :method
{
   my $self = shift;
   return $self-&gt;SUPER::socket(@_) if not defined $self-&gt;fileno;

   # I hate core prototypes sometimes...
   socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef;

   dup2( $tmph-&gt;fileno, $self-&gt;fileno ) or die "Unable to dup2 $tmph onto $self - $!";
}

# Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an
#   -&gt;fdopen call. In this case we'll apply a fix
BEGIN {
   if( eval($IO::Socket::VERSION) &lt; 1.35 ) {
      *socktype = sub {
         my $self = shift;
         my $type = $self-&gt;SUPER::socktype;
         if( !defined $type ) {
            $type = $self-&gt;sockopt( Socket::SO_TYPE() );
         }
         return $type;
      };
   }
}

=head2 $inet = $sock-&gt;as_inet

Returns a new L&lt;IO::Socket::INET&gt; instance wrapping the same filehandle. This
may be useful in cases where it is required, for backward-compatibility, to
have a real object of C&lt;IO::Socket::INET&gt; type instead of C&lt;IO::Socket::IP&gt;.
The new object will wrap the same underlying socket filehandle as the
original, so care should be taken not to continue to use both objects
concurrently. Ideally the original C&lt;$sock&gt; should be discarded after this
method is called.

This method checks that the socket domain is C&lt;PF_INET&gt; and will throw an
exception if it isn't.

=cut

sub as_inet
{
   my $self = shift;
   croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self-&gt;sockdomain == AF_INET;
   return IO::Socket::INET-&gt;new_from_fd( $self-&gt;fileno, "r+" );
}

=head1 NON-BLOCKING

If the constructor is passed a defined but false value for the C&lt;Blocking&gt;
argument then the socket is put into non-blocking mode. When in non-blocking
mode, the socket will not be set up by the time the constructor returns,
because the underlying C&lt;connect(2)&gt; syscall would otherwise have to block.

The non-blocking behaviour is an extension of the C&lt;IO::Socket::INET&gt; API,
unique to C&lt;IO::Socket::IP&gt;, because the former does not support multi-homed
non-blocking connect.

When using non-blocking mode, the caller must repeatedly check for
writeability on the filehandle (for instance using C&lt;select&gt; or C&lt;IO::Poll&gt;).
Each time the filehandle is ready to write, the C&lt;connect&gt; method must be
called, with no arguments. Note that some operating systems, most notably
C&lt;MSWin32&gt; do not report a C&lt;connect()&gt; failure using write-ready; so you must
also C&lt;select()&gt; for exceptional status.

While C&lt;connect&gt; returns false, the value of C&lt;$!&gt; indicates whether it should
be tried again (by being set to the value C&lt;EINPROGRESS&gt;, or C&lt;EWOULDBLOCK&gt; on
MSWin32), or whether a permanent error has occurred (e.g. C&lt;ECONNREFUSED&gt;).

Once the socket has been connected to the peer, C&lt;connect&gt; will return true
and the socket will now be ready to use.

Note that calls to the platform's underlying C&lt;getaddrinfo(3)&gt; function may
block. If C&lt;IO::Socket::IP&gt; has to perform this lookup, the constructor will
block even when in non-blocking mode.

To avoid this blocking behaviour, the caller should pass in the result of such
a lookup using the C&lt;PeerAddrInfo&gt; or C&lt;LocalAddrInfo&gt; arguments. This can be
achieved by using L&lt;Net::LibAsyncNS&gt;, or the C&lt;getaddrinfo(3)&gt; function can be
called in a child process.

 use IO::Socket::IP;
 use Errno qw( EINPROGRESS EWOULDBLOCK );

 my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here

 my $socket = IO::Socket::IP-&gt;new(
    PeerAddrInfo =&gt; \@peeraddrinfo,
    Blocking     =&gt; 0,
 ) or die "Cannot construct socket - $@";

 while( !$socket-&gt;connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
    my $wvec = '';
    vec( $wvec, fileno $socket, 1 ) = 1;
    my $evec = '';
    vec( $evec, fileno $socket, 1 ) = 1;

    select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
 }

 die "Cannot connect - $!" if $!;

 ...

The example above uses C&lt;select()&gt;, but any similar mechanism should work
analogously. C&lt;IO::Socket::IP&gt; takes care when creating new socket filehandles
to preserve the actual file descriptor number, so such techniques as C&lt;poll&gt;
or C&lt;epoll&gt; should be transparent to its reallocation of a different socket
underneath, perhaps in order to switch protocol family between C&lt;PF_INET&gt; and
C&lt;PF_INET6&gt;.

For another example using C&lt;IO::Poll&gt; and C&lt;Net::LibAsyncNS&gt;, see the
F&lt;examples/nonblocking_libasyncns.pl&gt; file in the module distribution.

=cut

=head1 C&lt;PeerHost&gt; AND C&lt;LocalHost&gt; PARSING

To support the C&lt;IO::Socket::INET&gt; API, the host and port information may be
passed in a single string rather than as two separate arguments.

If either C&lt;LocalHost&gt; or C&lt;PeerHost&gt; (or their C&lt;...Addr&gt; synonyms) have any
of the following special forms then special parsing is applied.

The value of the C&lt;...Host&gt; argument will be split to give both the hostname
and port (or service name):

 hostname.example.org:http    # Host name
 192.0.2.1:80                 # IPv4 address
 [2001:db8::1]:80             # IPv6 address

In each case, the port or service name (e.g. C&lt;80&gt;) is passed as the
C&lt;LocalService&gt; or C&lt;PeerService&gt; argument.

Either of C&lt;LocalService&gt; or C&lt;PeerService&gt; (or their C&lt;...Port&gt; synonyms) can
be either a service name, a decimal number, or a string containing both a
service name and number, in a form such as

 http(80)

In this case, the name (C&lt;http&gt;) will be tried first, but if the resolver does
not understand it then the port number (C&lt;80&gt;) will be used instead.

If the C&lt;...Host&gt; argument is in this special form and the corresponding
C&lt;...Service&gt; or C&lt;...Port&gt; argument is also defined, the one parsed from
the C&lt;...Host&gt; argument will take precedence and the other will be ignored.

=head2 ( $host, $port ) = IO::Socket::IP-&gt;split_addr( $addr )

Utility method that provides the parsing functionality described above.
Returns a 2-element list, containing either the split hostname and port
description if it could be parsed, or the given address and C&lt;undef&gt; if it was
not recognised.

 IO::Socket::IP-&gt;split_addr( "hostname:http" )
                              # ( "hostname",  "http" )

 IO::Socket::IP-&gt;split_addr( "192.0.2.1:80" )
                              # ( "192.0.2.1", "80"   )

 IO::Socket::IP-&gt;split_addr( "[2001:db8::1]:80" )
                              # ( "2001:db8::1", "80" )

 IO::Socket::IP-&gt;split_addr( "something.else" )
                              # ( "something.else", undef )

=cut

sub split_addr
{
   shift;
   my ( $addr ) = @_;

   local ( $1, $2 ); # Placate a taint-related bug; [perl #67962]
   if( $addr =~ m/\A\[($IPv6_re)\](?::([^\s:]*))?\z/ or
       $addr =~ m/\A([^\s:]*):([^\s:]*)\z/ ) {
      return ( $1, $2 ) if defined $2 and length $2;
      return ( $1, undef );
   }

   return ( $addr, undef );
}

=head2 $addr = IO::Socket::IP-&gt;join_addr( $host, $port )

Utility method that performs the reverse of C&lt;split_addr&gt;, returning a string
formed by joining the specified host address and port number. The host address
will be wrapped in C&lt;[]&gt; brackets if required (because it is a raw IPv6
numeric address).

This can be especially useful when combined with the C&lt;sockhost_service&gt; or
C&lt;peerhost_service&gt; methods.

 say "Connected to ", IO::Socket::IP-&gt;join_addr( $sock-&gt;peerhost_service );

=cut

sub join_addr
{
   shift;
   my ( $host, $port ) = @_;

   $host = "[$host]" if $host =~ m/:/;

   return join ":", $host, $port if defined $port;
   return $host;
}

# Since IO::Socket-&gt;new( Domain =&gt; ... ) will delete the Domain parameter
# before calling -&gt;configure, we need to keep track of which it was

package # hide from indexer
   IO::Socket::IP::_ForINET;
use base qw( IO::Socket::IP );

sub configure
{
   # This is evil
   my $self = shift;
   my ( $arg ) = @_;

   bless $self, "IO::Socket::IP";
   $self-&gt;configure( { %$arg, Family =&gt; Socket::AF_INET() } );
}

package # hide from indexer
   IO::Socket::IP::_ForINET6;
use base qw( IO::Socket::IP );

sub configure
{
   # This is evil
   my $self = shift;
   my ( $arg ) = @_;

   bless $self, "IO::Socket::IP";
   $self-&gt;configure( { %$arg, Family =&gt; Socket::AF_INET6() } );
}

=head1 C&lt;IO::Socket::INET&gt; INCOMPATIBILITES

=over 4

=item *

The behaviour enabled by C&lt;MultiHomed&gt; is in fact implemented by
C&lt;IO::Socket::IP&gt; as it is required to correctly support searching for a
useable address from the results of the C&lt;getaddrinfo(3)&gt; call. The
constructor will ignore the value of this argument, except if it is defined
but false. An exception is thrown in this case, because that would request it
disable the C&lt;getaddrinfo(3)&gt; search behaviour in the first place.

=item *

C&lt;IO::Socket::IP&gt; implements both the C&lt;Blocking&gt; and C&lt;Timeout&gt; parameters,
but it implements the interaction of both in a different way.

In C&lt;::INET&gt;, supplying a timeout overrides the non-blocking behaviour,
meaning that the C&lt;connect()&gt; operation will still block despite that the
caller asked for a non-blocking socket. This is not explicitly specified in
its documentation, nor does this author believe that is a useful behaviour -
it appears to come from a quirk of implementation.

In C&lt;::IP&gt; therefore, the C&lt;Blocking&gt; parameter takes precedence - if a
non-blocking socket is requested, no operation will block. The C&lt;Timeout&gt;
parameter here simply defines the maximum time that a blocking C&lt;connect()&gt;
call will wait, if it blocks at all.

In order to specifically obtain the "blocking connect then non-blocking send
and receive" behaviour of specifying this combination of options to C&lt;::INET&gt;
when using C&lt;::IP&gt;, perform first a blocking connect, then afterwards turn the
socket into nonblocking mode.

 my $sock = IO::Socket::IP-&gt;new(
    PeerHost =&gt; $peer,
    Timeout =&gt; 20,
 ) or die "Cannot connect - $@";

 $sock-&gt;blocking( 0 );

This code will behave identically under both C&lt;IO::Socket::INET&gt; and
C&lt;IO::Socket::IP&gt;.

=back

=cut

=head1 TODO

=over 4

=item *

Investigate whether C&lt;POSIX::dup2&gt; upsets BSD's C&lt;kqueue&gt; watchers, and if so,
consider what possible workarounds might be applied.

=back

=head1 AUTHOR

Paul Evans &lt;leonerd@leonerd.org.uk&gt;

=cut

0x55AA;
</pre></body></html>