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)
4 # (C) Paul Evans, 2010-2014 -- leonerd@leonerd.org.uk
6 package IO::Socket::IP;
7 # $VERSION needs to be set before use base 'IO::Socket'
8 # - https://rt.cpan.org/Ticket/Display.html?id=92107
15 use base qw( IO::Socket );
20 getaddrinfo getnameinfo
24 IPPROTO_TCP IPPROTO_UDP
25 IPPROTO_IPV6 IPV6_V6ONLY
26 NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV
27 SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR
28 SOCK_DGRAM SOCK_STREAM
31 my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined
32 my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0;
34 use Errno qw( EINVAL EINPROGRESS EISCONN ETIMEDOUT EWOULDBLOCK );
36 use constant HAVE_MSWIN32 => ( $^O eq "MSWin32" );
38 # At least one OS (Android) is known not to have getprotobyname()
39 use constant HAVE_GETPROTOBYNAME => defined eval { getprotobyname( "tcp" ) };
42 # translation of RFC 3986 3.2.2 ABNF to re
43 my $IPv4address = do {
44 my $dec_octet = q<(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])>;
45 qq<$dec_octet(?: \\. $dec_octet){3}>;
47 my $IPv6address = do {
48 my $h16 = qq<[0-9A-Fa-f]{1,4}>;
49 my $ls32 = qq<(?: $h16 : $h16 | $IPv4address)>;
52 | :: (?: $h16 : ){5} $ls32
53 | (?: $h16 )? :: (?: $h16 : ){4} $ls32
54 | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32
55 | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32
56 | (?: (?: $h16 : ){0,3} $h16 )? :: $h16 : $ls32
57 | (?: (?: $h16 : ){0,4} $h16 )? :: $ls32
58 | (?: (?: $h16 : ){0,5} $h16 )? :: $h16
59 | (?: (?: $h16 : ){0,6} $h16 )? ::
67 C<IO::Socket::IP> - Family-neutral IP socket supporting both IPv4 and IPv6
73 my $sock = IO::Socket::IP->new(
74 PeerHost => "www.google.com",
77 ) or die "Cannot construct socket - $@";
79 my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
80 ( $sock->sockdomain == PF_INET ) ? "IPv4" :
83 printf "Connected to google via %s\n", $familyname;
87 This module provides a protocol-independent way to use IPv4 and IPv6 sockets,
88 intended as a replacement for L<IO::Socket::INET>. Most constructor arguments
89 and methods are provided in a backward-compatible way. For a list of known
90 differences, see the C<IO::Socket::INET> INCOMPATIBILITES section below.
92 It uses the C<getaddrinfo(3)> function to convert hostnames and service names
93 or port numbers into sets of possible addresses to connect to or listen on.
94 This allows it to work for IPv6 where the system supports it, while still
95 falling back to IPv4-only on systems which don't.
97 =head1 REPLACING C<IO::Socket> DEFAULT BEHAVIOUR
99 By placing C<-register> in the import list, L<IO::Socket> uses
100 C<IO::Socket::IP> rather than C<IO::Socket::INET> as the class that handles
101 C<PF_INET>. C<IO::Socket> will also use C<IO::Socket::IP> rather than
102 C<IO::Socket::INET6> to handle C<PF_INET6>, provided that the C<AF_INET6>
103 constant is available.
105 Changing C<IO::Socket>'s default behaviour means that calling the
106 C<IO::Socket> constructor with either C<PF_INET> or C<PF_INET6> as the
107 C<Domain> parameter will yield an C<IO::Socket::IP> object.
109 use IO::Socket::IP -register;
111 my $sock = IO::Socket->new(
115 ) or die "Cannot create socket - $@\n";
117 print "Created a socket of type " . ref($sock) . "\n";
119 Note that C<-register> is a global setting that applies to the entire program;
120 it cannot be applied only for certain callers, removed, or limited by lexical
131 if( $_ eq "-register" ) {
132 IO::Socket::IP::_ForINET->register_domain( AF_INET );
133 IO::Socket::IP::_ForINET6->register_domain( $AF_INET6 ) if defined $AF_INET6;
140 @_ = ( $pkg, @symbols );
141 goto &IO::Socket::import;
144 # Convenient capability test function
146 my $can_disable_v6only;
147 sub CAN_DISABLE_V6ONLY
149 return $can_disable_v6only if defined $can_disable_v6only;
151 socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or
152 die "Cannot socket(PF_INET6) - $!";
154 if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) {
155 return $can_disable_v6only = 1;
157 elsif( $! == EINVAL ) {
158 return $can_disable_v6only = 0;
161 die "Cannot setsockopt() - $!";
170 =head2 $sock = IO::Socket::IP->new( %args )
172 Creates a new C<IO::Socket::IP> object, containing a newly created socket
173 handle according to the named arguments passed. The recognised arguments are:
177 =item PeerHost => STRING
179 =item PeerService => STRING
181 Hostname and service name for the peer to C<connect()> to. The service name
182 may be given as a port number, as a decimal string.
184 =item PeerAddr => STRING
186 =item PeerPort => STRING
188 For symmetry with the accessor methods and compatibility with
189 C<IO::Socket::INET>, these are accepted as synonyms for C<PeerHost> and
190 C<PeerService> respectively.
192 =item PeerAddrInfo => ARRAY
194 Alternate form of specifying the peer to C<connect()> to. This should be an
195 array of the form returned by C<Socket::getaddrinfo>.
197 This parameter takes precedence over the C<Peer*>, C<Family>, C<Type> and
200 =item LocalHost => STRING
202 =item LocalService => STRING
204 Hostname and service name for the local address to C<bind()> to.
206 =item LocalAddr => STRING
208 =item LocalPort => STRING
210 For symmetry with the accessor methods and compatibility with
211 C<IO::Socket::INET>, these are accepted as synonyms for C<LocalHost> and
212 C<LocalService> respectively.
214 =item LocalAddrInfo => ARRAY
216 Alternate form of specifying the local address to C<bind()> to. This should be
217 an array of the form returned by C<Socket::getaddrinfo>.
219 This parameter takes precedence over the C<Local*>, C<Family>, C<Type> and
224 The address family to pass to C<getaddrinfo> (e.g. C<AF_INET>, C<AF_INET6>).
225 Normally this will be left undefined, and C<getaddrinfo> will search using any
226 address family supported by the system.
230 The socket type to pass to C<getaddrinfo> (e.g. C<SOCK_STREAM>,
231 C<SOCK_DGRAM>). Normally defined by the caller; if left undefined
232 C<getaddrinfo> may attempt to infer the type from the service name.
234 =item Proto => STRING or INT
236 The IP protocol to use for the socket (e.g. C<'tcp'>, C<IPPROTO_TCP>,
237 C<'udp'>,C<IPPROTO_UDP>). Normally this will be left undefined, and either
238 C<getaddrinfo> or the kernel will choose an appropriate value. May be given
239 either in string name or numeric form.
241 =item GetAddrInfoFlags => INT
243 More flags to pass to the C<getaddrinfo()> function. If not supplied, a
244 default of C<AI_ADDRCONFIG> will be used.
246 These flags will be combined with C<AI_PASSIVE> if the C<Listen> argument is
247 given. For more information see the documentation about C<getaddrinfo()> in
248 the L<Socket> module.
252 If defined, puts the socket into listening mode where new connections can be
253 accepted using the C<accept> method. The value given is used as the
254 C<listen(2)> queue size.
256 =item ReuseAddr => BOOL
258 If true, set the C<SO_REUSEADDR> sockopt
260 =item ReusePort => BOOL
262 If true, set the C<SO_REUSEPORT> sockopt (not all OSes implement this sockopt)
264 =item Broadcast => BOOL
266 If true, set the C<SO_BROADCAST> sockopt
270 If defined, set the C<IPV6_V6ONLY> sockopt when creating C<PF_INET6> sockets
271 to the given value. If true, a listening-mode socket will only listen on the
272 C<AF_INET6> addresses; if false it will also accept connections from
273 C<AF_INET> addresses.
275 If not defined, the socket option will not be changed, and default value set
276 by the operating system will apply. For repeatable behaviour across platforms
277 it is recommended this value always be defined for listening-mode sockets.
279 Note that not all platforms support disabling this option. Some, at least
280 OpenBSD and MirBSD, will fail with C<EINVAL> if you attempt to disable it.
281 To determine whether it is possible to disable, you may use the class method
283 if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
290 If your platform does not support disabling this option but you still want to
291 listen for both C<AF_INET> and C<AF_INET6> connections you will have to create
292 two listening sockets, one bound to each protocol.
296 This C<IO::Socket::INET>-style argument is ignored, except if it is defined
297 but false. See the C<IO::Socket::INET> INCOMPATIBILITES section below.
299 However, the behaviour it enables is always performed by C<IO::Socket::IP>.
301 =item Blocking => BOOL
303 If defined but false, the socket will be set to non-blocking mode. Otherwise
304 it will default to blocking mode. See the NON-BLOCKING section below for more
309 If defined, gives a maximum time in seconds to block per C<connect()> call
310 when in blocking mode. If missing, no timeout is applied other than that
311 provided by the underlying operating system. When in non-blocking mode this
312 parameter is ignored.
314 Note that if the hostname resolves to multiple address candidates, the same
315 timeout will apply to each connection attempt individually, rather than to the
316 operation as a whole. Further note that the timeout does not apply to the
317 initial hostname resolve operation, if connecting by hostname.
319 This behviour is copied inspired by C<IO::Socket::INET>; for more fine grained
320 control over connection timeouts, consider performing a nonblocking connect
325 If neither C<Type> nor C<Proto> hints are provided, a default of
326 C<SOCK_STREAM> and C<IPPROTO_TCP> respectively will be set, to maintain
327 compatibility with C<IO::Socket::INET>. Other named arguments that are not
328 recognised are ignored.
330 If neither C<Family> nor any hosts or addresses are passed, nor any
331 C<*AddrInfo>, then the constructor has no information on which to decide a
332 socket family to create. In this case, it performs a C<getaddinfo> call with
333 the C<AI_ADDRCONFIG> flag, no host name, and a service name of C<"0">, and
334 uses the family of the first returned result.
336 If the constructor fails, it will set C<$@> to an appropriate error message;
337 this may be from C<$!> or it may be some other string; not every failure
338 necessarily has an associated C<errno> value.
340 =head2 $sock = IO::Socket::IP->new( $peeraddr )
342 As a special case, if the constructor is passed a single argument (as
343 opposed to an even-sized list of key/value pairs), it is taken to be the value
344 of the C<PeerAddr> parameter. This is parsed in the same way, according to the
345 behaviour given in the C<PeerHost> AND C<LocalHost> PARSING section below.
352 my %arg = (@_ == 1) ? (PeerHost => $_[0]) : @_;
353 return $class->SUPER::new(%arg);
356 # IO::Socket may call this one; neaten up the arguments from IO::Socket::INET
357 # before calling our real _configure method
363 $arg->{PeerHost} = delete $arg->{PeerAddr}
364 if exists $arg->{PeerAddr} && !exists $arg->{PeerHost};
366 $arg->{PeerService} = delete $arg->{PeerPort}
367 if exists $arg->{PeerPort} && !exists $arg->{PeerService};
369 $arg->{LocalHost} = delete $arg->{LocalAddr}
370 if exists $arg->{LocalAddr} && !exists $arg->{LocalHost};
372 $arg->{LocalService} = delete $arg->{LocalPort}
373 if exists $arg->{LocalPort} && !exists $arg->{LocalService};
375 for my $type (qw(Peer Local)) {
376 my $host = $type . 'Host';
377 my $service = $type . 'Service';
379 if( defined $arg->{$host} ) {
380 ( $arg->{$host}, my $s ) = $self->split_addr( $arg->{$host} );
381 # IO::Socket::INET compat - *Host parsed port always takes precedence
382 $arg->{$service} = $s if defined $s;
386 $self->_io_socket_ip__configure( $arg );
389 # Avoid simply calling it _configure, as some subclasses of IO::Socket::INET on CPAN already take that
390 sub _io_socket_ip__configure
399 if( defined $arg->{GetAddrInfoFlags} ) {
400 $hints{flags} = $arg->{GetAddrInfoFlags};
403 $hints{flags} = $AI_ADDRCONFIG;
406 if( defined( my $family = $arg->{Family} ) ) {
407 $hints{family} = $family;
410 if( defined( my $type = $arg->{Type} ) ) {
411 $hints{socktype} = $type;
414 if( defined( my $proto = $arg->{Proto} ) ) {
415 unless( $proto =~ m/^\d+$/ ) {
416 my $protonum = HAVE_GETPROTOBYNAME
417 ? getprotobyname( $proto )
418 : eval { Socket->${\"IPPROTO_\U$proto"}() };
419 defined $protonum or croak "Unrecognised protocol $proto";
423 $hints{protocol} = $proto;
426 # To maintain compatibility with IO::Socket::INET, imply a default of
427 # SOCK_STREAM + IPPROTO_TCP if neither hint is given
428 if( !defined $hints{socktype} and !defined $hints{protocol} ) {
429 $hints{socktype} = SOCK_STREAM;
430 $hints{protocol} = IPPROTO_TCP;
433 # Some OSes (NetBSD) don't seem to like just a protocol hint without a
434 # socktype hint as well. We'll set a couple of common ones
435 if( !defined $hints{socktype} and defined $hints{protocol} ) {
436 $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP;
437 $hints{socktype} = SOCK_DGRAM if $hints{protocol} == IPPROTO_UDP;
440 if( my $info = $arg->{LocalAddrInfo} ) {
441 ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref";
442 @localinfos = @$info;
444 elsif( defined $arg->{LocalHost} or defined $arg->{LocalService} ) {
445 # Either may be undef
446 my $host = $arg->{LocalHost};
447 my $service = $arg->{LocalService};
449 local $1; # Placate a taint-related bug; [perl #67962]
450 defined $service and $service =~ s/\((\d+)\)$// and
451 my $fallback_port = $1;
453 my %localhints = %hints;
454 $localhints{flags} |= AI_PASSIVE;
455 ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints );
457 if( $err and defined $fallback_port ) {
458 ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints );
468 if( my $info = $arg->{PeerAddrInfo} ) {
469 ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref";
472 elsif( defined $arg->{PeerHost} or defined $arg->{PeerService} ) {
473 defined( my $host = $arg->{PeerHost} ) or
474 croak "Expected 'PeerHost'";
475 defined( my $service = $arg->{PeerService} ) or
476 croak "Expected 'PeerService'";
478 local $1; # Placate a taint-related bug; [perl #67962]
479 defined $service and $service =~ s/\((\d+)\)$// and
480 my $fallback_port = $1;
482 ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints );
484 if( $err and defined $fallback_port ) {
485 ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints );
495 my @sockopts_enabled;
496 push @sockopts_enabled, SO_REUSEADDR if $arg->{ReuseAddr};
497 push @sockopts_enabled, SO_REUSEPORT if $arg->{ReusePort};
498 push @sockopts_enabled, SO_BROADCAST if $arg->{Broadcast};
500 my $listenqueue = $arg->{Listen};
502 croak "Cannot Listen with a PeerHost" if defined $listenqueue and @peerinfos;
504 my $blocking = $arg->{Blocking};
505 defined $blocking or $blocking = 1;
507 my $v6only = $arg->{V6Only};
509 # IO::Socket::INET defines this key. IO::Socket::IP always implements the
510 # behaviour it requests, so we can ignore it, unless the caller is for some
511 # reason asking to disable it.
512 if( defined $arg->{MultiHomed} and !$arg->{MultiHomed} ) {
513 croak "Cannot disable the MultiHomed parameter";
517 foreach my $local ( @localinfos ? @localinfos : {} ) {
518 foreach my $peer ( @peerinfos ? @peerinfos : {} ) {
519 next if defined $local->{family} and defined $peer->{family} and
520 $local->{family} != $peer->{family};
521 next if defined $local->{socktype} and defined $peer->{socktype} and
522 $local->{socktype} != $peer->{socktype};
523 next if defined $local->{protocol} and defined $peer->{protocol} and
524 $local->{protocol} != $peer->{protocol};
526 my $family = $local->{family} || $peer->{family} or next;
527 my $socktype = $local->{socktype} || $peer->{socktype} or next;
528 my $protocol = $local->{protocol} || $peer->{protocol} || 0;
532 socktype => $socktype,
533 protocol => $protocol,
534 localaddr => $local->{addr},
535 peeraddr => $peer->{addr},
541 # If there was a Family hint then create a plain unbound, unconnected socket
542 if( defined $hints{family} ) {
544 family => $hints{family},
545 socktype => $hints{socktype},
546 protocol => $hints{protocol},
549 # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a
550 # suitable family first.
552 ( my $err, @infos ) = getaddrinfo( "", "0", \%hints );
559 # We'll take all the @infos anyway, because some OSes (HPUX) are known to
560 # ignore the AI_ADDRCONFIG hint and return AF_INET6 even if they don't
565 # In the nonblocking case, caller will be calling ->setup multiple times.
566 # Store configuration in the object for the ->setup method
567 # Yes, these are messy. Sorry, I can't help that...
569 ${*$self}{io_socket_ip_infos} = \@infos;
571 ${*$self}{io_socket_ip_idx} = -1;
573 ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled;
574 ${*$self}{io_socket_ip_v6only} = $v6only;
575 ${*$self}{io_socket_ip_listenqueue} = $listenqueue;
576 ${*$self}{io_socket_ip_blocking} = $blocking;
578 ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ];
580 # ->setup is allowed to return false in nonblocking mode
581 $self->setup or !$blocking or return undef;
591 ${*$self}{io_socket_ip_idx}++;
592 last if ${*$self}{io_socket_ip_idx} >= @{ ${*$self}{io_socket_ip_infos} };
594 my $info = ${*$self}{io_socket_ip_infos}->[${*$self}{io_socket_ip_idx}];
596 $self->socket( @{$info}{qw( family socktype protocol )} ) or
597 ( ${*$self}{io_socket_ip_errors}[2] = $!, next );
599 $self->blocking( 0 ) unless ${*$self}{io_socket_ip_blocking};
601 foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) {
602 $self->setsockopt( SOL_SOCKET, $sockopt, pack "i", 1 ) or ( $@ = "$!", return undef );
605 if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info->{family} == $AF_INET6 ) {
606 my $v6only = ${*$self}{io_socket_ip_v6only};
607 $self->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or ( $@ = "$!", return undef );
610 if( defined( my $addr = $info->{localaddr} ) ) {
611 $self->bind( $addr ) or
612 ( ${*$self}{io_socket_ip_errors}[1] = $!, next );
615 if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) {
616 $self->listen( $listenqueue ) or ( $@ = "$!", return undef );
619 if( defined( my $addr = $info->{peeraddr} ) ) {
620 if( $self->connect( $addr ) ) {
625 if( $! == EINPROGRESS or HAVE_MSWIN32 && $! == Errno::EWOULDBLOCK() ) {
626 ${*$self}{io_socket_ip_connect_in_progress} = 1;
630 # If connect failed but we have no system error there must be an error
631 # at the application layer, like a bad certificate with
633 # In this case don't continue IP based multi-homing because the problem
634 # cannot be solved at the IP layer.
637 ${*$self}{io_socket_ip_errors}[0] = $!;
644 # Pick the most appropriate error, stringified
645 $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0];
654 # It seems that IO::Socket hides EINPROGRESS errors, making them look like
655 # a success. This is annoying here.
656 # Instead of putting up with its frankly-irritating intentional breakage of
657 # useful APIs I'm just going to end-run around it and call CORE::connect()
663 # Annoyingly IO::Socket's connect() is where the timeout logic is
664 # implemented, so we'll have to reinvent it here
665 my $timeout = ${*$self}{'io_socket_timeout'};
667 return CORE::connect( $self, $addr ) unless defined $timeout;
669 my $was_blocking = $self->blocking( 0 );
671 my $err = defined CORE::connect( $self, $addr ) ? 0 : $!+0;
677 elsif( not( $err == EINPROGRESS or $err == EWOULDBLOCK ) ) {
678 # Failed for some other reason
681 elsif( !$was_blocking ) {
682 # We shouldn't block anyway
686 my $vec = ''; vec( $vec, $self->fileno, 1 ) = 1;
687 if( !select( $vec, $vec, $vec, $timeout ) ) {
692 # Hoist the error by connect()ing a second time
693 $err = defined CORE::connect( $self, $addr ) ? 0 : $!+0;
694 $err = 0 if $err == EISCONN; # Some OSes give EISCONN
696 $self->blocking( $was_blocking );
698 $! = $err, return undef if $err;
702 return 1 if !${*$self}{io_socket_ip_connect_in_progress};
704 # See if a connect attempt has just failed with an error
705 if( my $errno = $self->getsockopt( SOL_SOCKET, SO_ERROR ) ) {
706 delete ${*$self}{io_socket_ip_connect_in_progress};
707 ${*$self}{io_socket_ip_errors}[0] = $! = $errno;
711 # No error, so either connect is still in progress, or has completed
712 # successfully. We can tell by trying to connect() again; either it will
713 # succeed or we'll get EISCONN (connected successfully), or EALREADY
714 # (still in progress). This even works on MSWin32.
715 my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr};
717 if( CORE::connect( $self, $addr ) or $! == EISCONN ) {
718 delete ${*$self}{io_socket_ip_connect_in_progress};
731 return defined $self->fileno &&
732 !${*$self}{io_socket_ip_connect_in_progress} &&
733 defined getpeername( $self ); # ->peername caches, we need to detect disconnection
738 As well as the following methods, this class inherits all the methods in
739 L<IO::Socket> and L<IO::Handle>.
743 sub _get_host_service
746 my ( $addr, $flags, $xflags ) = @_;
748 $flags |= NI_DGRAM if $self->socktype == SOCK_DGRAM;
750 my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 );
751 croak "getnameinfo - $err" if $err;
753 return ( $host, $service );
759 my $family = sockaddr_family $addr;
761 if( $family == AF_INET ) {
762 return ( Socket::unpack_sockaddr_in( $addr ) )[1];
764 elsif( defined $AF_INET6 and $family == $AF_INET6 ) {
765 return ( Socket::unpack_sockaddr_in6( $addr ) )[1];
768 croak "Unrecognised address family $family";
772 =head2 ( $host, $service ) = $sock->sockhost_service( $numeric )
774 Returns the hostname and service name of the local address (that is, the
775 socket address given by the C<sockname> method).
777 If C<$numeric> is true, these will be given in numeric form rather than being
780 The following four convenience wrappers may be used to obtain one of the two
781 values returned here. If both host and service names are required, this method
782 is preferable to the following wrappers, because it will call
783 C<getnameinfo(3)> only once.
790 my ( $numeric ) = @_;
792 $self->_get_host_service( $self->sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
795 =head2 $addr = $sock->sockhost
797 Return the numeric form of the local address as a textual representation
799 =head2 $port = $sock->sockport
801 Return the numeric form of the local port number
803 =head2 $host = $sock->sockhostname
805 Return the resolved name of the local address
807 =head2 $service = $sock->sockservice
809 Return the resolved name of the local port number
813 sub sockhost { my $self = shift; ( $self->_get_host_service( $self->sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
814 sub sockport { my $self = shift; ( $self->_get_host_service( $self->sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] }
816 sub sockhostname { my $self = shift; ( $self->_get_host_service( $self->sockname, 0, NIx_NOSERV ) )[0] }
817 sub sockservice { my $self = shift; ( $self->_get_host_service( $self->sockname, 0, NIx_NOHOST ) )[1] }
819 =head2 $addr = $sock->sockaddr
821 Return the local address as a binary octet string
825 sub sockaddr { my $self = shift; _unpack_sockaddr $self->sockname }
827 =head2 ( $host, $service ) = $sock->peerhost_service( $numeric )
829 Returns the hostname and service name of the peer address (that is, the
830 socket address given by the C<peername> method), similar to the
831 C<sockhost_service> method.
833 The following four convenience wrappers may be used to obtain one of the two
834 values returned here. If both host and service names are required, this method
835 is preferable to the following wrappers, because it will call
836 C<getnameinfo(3)> only once.
843 my ( $numeric ) = @_;
845 $self->_get_host_service( $self->peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 );
848 =head2 $addr = $sock->peerhost
850 Return the numeric form of the peer address as a textual representation
852 =head2 $port = $sock->peerport
854 Return the numeric form of the peer port number
856 =head2 $host = $sock->peerhostname
858 Return the resolved name of the peer address
860 =head2 $service = $sock->peerservice
862 Return the resolved name of the peer port number
866 sub peerhost { my $self = shift; ( $self->_get_host_service( $self->peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] }
867 sub peerport { my $self = shift; ( $self->_get_host_service( $self->peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] }
869 sub peerhostname { my $self = shift; ( $self->_get_host_service( $self->peername, 0, NIx_NOSERV ) )[0] }
870 sub peerservice { my $self = shift; ( $self->_get_host_service( $self->peername, 0, NIx_NOHOST ) )[1] }
872 =head2 $addr = $peer->peeraddr
874 Return the peer address as a binary octet string
878 sub peeraddr { my $self = shift; _unpack_sockaddr $self->peername }
880 # This unbelievably dodgy hack works around the bug that IO::Socket doesn't do
882 # https://rt.cpan.org/Ticket/Display.html?id=61577
886 my ( $new, $peer ) = $self->SUPER::accept( @_ ) or return;
888 ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto );
890 return wantarray ? ( $new, $peer )
894 # This second unbelievably dodgy hack guarantees that $self->fileno doesn't
895 # change, which is useful during nonblocking connect
899 return $self->SUPER::socket(@_) if not defined $self->fileno;
901 # I hate core prototypes sometimes...
902 CORE::socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef;
904 dup2( $tmph->fileno, $self->fileno ) or die "Unable to dup2 $tmph onto $self - $!";
907 # Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an
908 # ->fdopen call. In this case we'll apply a fix
910 if( $IO::Socket::VERSION < 1.35 ) {
913 my $type = $self->SUPER::socktype;
914 if( !defined $type ) {
915 $type = $self->sockopt( Socket::SO_TYPE() );
922 =head2 $inet = $sock->as_inet
924 Returns a new L<IO::Socket::INET> instance wrapping the same filehandle. This
925 may be useful in cases where it is required, for backward-compatibility, to
926 have a real object of C<IO::Socket::INET> type instead of C<IO::Socket::IP>.
927 The new object will wrap the same underlying socket filehandle as the
928 original, so care should be taken not to continue to use both objects
929 concurrently. Ideally the original C<$sock> should be discarded after this
932 This method checks that the socket domain is C<PF_INET> and will throw an
933 exception if it isn't.
940 croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self->sockdomain == AF_INET;
941 return IO::Socket::INET->new_from_fd( $self->fileno, "r+" );
946 If the constructor is passed a defined but false value for the C<Blocking>
947 argument then the socket is put into non-blocking mode. When in non-blocking
948 mode, the socket will not be set up by the time the constructor returns,
949 because the underlying C<connect(2)> syscall would otherwise have to block.
951 The non-blocking behaviour is an extension of the C<IO::Socket::INET> API,
952 unique to C<IO::Socket::IP>, because the former does not support multi-homed
953 non-blocking connect.
955 When using non-blocking mode, the caller must repeatedly check for
956 writeability on the filehandle (for instance using C<select> or C<IO::Poll>).
957 Each time the filehandle is ready to write, the C<connect> method must be
958 called, with no arguments. Note that some operating systems, most notably
959 C<MSWin32> do not report a C<connect()> failure using write-ready; so you must
960 also C<select()> for exceptional status.
962 While C<connect> returns false, the value of C<$!> indicates whether it should
963 be tried again (by being set to the value C<EINPROGRESS>, or C<EWOULDBLOCK> on
964 MSWin32), or whether a permanent error has occurred (e.g. C<ECONNREFUSED>).
966 Once the socket has been connected to the peer, C<connect> will return true
967 and the socket will now be ready to use.
969 Note that calls to the platform's underlying C<getaddrinfo(3)> function may
970 block. If C<IO::Socket::IP> has to perform this lookup, the constructor will
971 block even when in non-blocking mode.
973 To avoid this blocking behaviour, the caller should pass in the result of such
974 a lookup using the C<PeerAddrInfo> or C<LocalAddrInfo> arguments. This can be
975 achieved by using L<Net::LibAsyncNS>, or the C<getaddrinfo(3)> function can be
976 called in a child process.
979 use Errno qw( EINPROGRESS EWOULDBLOCK );
981 my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here
983 my $socket = IO::Socket::IP->new(
984 PeerAddrInfo => \@peeraddrinfo,
986 ) or die "Cannot construct socket - $@";
988 while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
990 vec( $wvec, fileno $socket, 1 ) = 1;
992 vec( $evec, fileno $socket, 1 ) = 1;
994 select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
997 die "Cannot connect - $!" if $!;
1001 The example above uses C<select()>, but any similar mechanism should work
1002 analogously. C<IO::Socket::IP> takes care when creating new socket filehandles
1003 to preserve the actual file descriptor number, so such techniques as C<poll>
1004 or C<epoll> should be transparent to its reallocation of a different socket
1005 underneath, perhaps in order to switch protocol family between C<PF_INET> and
1008 For another example using C<IO::Poll> and C<Net::LibAsyncNS>, see the
1009 F<examples/nonblocking_libasyncns.pl> file in the module distribution.
1013 =head1 C<PeerHost> AND C<LocalHost> PARSING
1015 To support the C<IO::Socket::INET> API, the host and port information may be
1016 passed in a single string rather than as two separate arguments.
1018 If either C<LocalHost> or C<PeerHost> (or their C<...Addr> synonyms) have any
1019 of the following special forms then special parsing is applied.
1021 The value of the C<...Host> argument will be split to give both the hostname
1022 and port (or service name):
1024 hostname.example.org:http # Host name
1025 192.0.2.1:80 # IPv4 address
1026 [2001:db8::1]:80 # IPv6 address
1028 In each case, the port or service name (e.g. C<80>) is passed as the
1029 C<LocalService> or C<PeerService> argument.
1031 Either of C<LocalService> or C<PeerService> (or their C<...Port> synonyms) can
1032 be either a service name, a decimal number, or a string containing both a
1033 service name and number, in a form such as
1037 In this case, the name (C<http>) will be tried first, but if the resolver does
1038 not understand it then the port number (C<80>) will be used instead.
1040 If the C<...Host> argument is in this special form and the corresponding
1041 C<...Service> or C<...Port> argument is also defined, the one parsed from
1042 the C<...Host> argument will take precedence and the other will be ignored.
1044 =head2 ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
1046 Utility method that provides the parsing functionality described above.
1047 Returns a 2-element list, containing either the split hostname and port
1048 description if it could be parsed, or the given address and C<undef> if it was
1051 IO::Socket::IP->split_addr( "hostname:http" )
1052 # ( "hostname", "http" )
1054 IO::Socket::IP->split_addr( "192.0.2.1:80" )
1055 # ( "192.0.2.1", "80" )
1057 IO::Socket::IP->split_addr( "[2001:db8::1]:80" )
1058 # ( "2001:db8::1", "80" )
1060 IO::Socket::IP->split_addr( "something.else" )
1061 # ( "something.else", undef )
1070 local ( $1, $2 ); # Placate a taint-related bug; [perl #67962]
1071 if( $addr =~ m/\A\[($IPv6_re)\](?::([^\s:]*))?\z/ or
1072 $addr =~ m/\A([^\s:]*):([^\s:]*)\z/ ) {
1073 return ( $1, $2 ) if defined $2 and length $2;
1074 return ( $1, undef );
1077 return ( $addr, undef );
1080 =head2 $addr = IO::Socket::IP->join_addr( $host, $port )
1082 Utility method that performs the reverse of C<split_addr>, returning a string
1083 formed by joining the specified host address and port number. The host address
1084 will be wrapped in C<[]> brackets if required (because it is a raw IPv6
1087 This can be especially useful when combined with the C<sockhost_service> or
1088 C<peerhost_service> methods.
1090 say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
1097 my ( $host, $port ) = @_;
1099 $host = "[$host]" if $host =~ m/:/;
1101 return join ":", $host, $port if defined $port;
1105 # Since IO::Socket->new( Domain => ... ) will delete the Domain parameter
1106 # before calling ->configure, we need to keep track of which it was
1108 package # hide from indexer
1109 IO::Socket::IP::_ForINET;
1110 use base qw( IO::Socket::IP );
1118 bless $self, "IO::Socket::IP";
1119 $self->configure( { %$arg, Family => Socket::AF_INET() } );
1122 package # hide from indexer
1123 IO::Socket::IP::_ForINET6;
1124 use base qw( IO::Socket::IP );
1132 bless $self, "IO::Socket::IP";
1133 $self->configure( { %$arg, Family => Socket::AF_INET6() } );
1136 =head1 C<IO::Socket::INET> INCOMPATIBILITES
1142 The behaviour enabled by C<MultiHomed> is in fact implemented by
1143 C<IO::Socket::IP> as it is required to correctly support searching for a
1144 useable address from the results of the C<getaddrinfo(3)> call. The
1145 constructor will ignore the value of this argument, except if it is defined
1146 but false. An exception is thrown in this case, because that would request it
1147 disable the C<getaddrinfo(3)> search behaviour in the first place.
1151 C<IO::Socket::IP> implements both the C<Blocking> and C<Timeout> parameters,
1152 but it implements the interaction of both in a different way.
1154 In C<::INET>, supplying a timeout overrides the non-blocking behaviour,
1155 meaning that the C<connect()> operation will still block despite that the
1156 caller asked for a non-blocking socket. This is not explicitly specified in
1157 its documentation, nor does this author believe that is a useful behaviour -
1158 it appears to come from a quirk of implementation.
1160 In C<::IP> therefore, the C<Blocking> parameter takes precedence - if a
1161 non-blocking socket is requested, no operation will block. The C<Timeout>
1162 parameter here simply defines the maximum time that a blocking C<connect()>
1163 call will wait, if it blocks at all.
1165 In order to specifically obtain the "blocking connect then non-blocking send
1166 and receive" behaviour of specifying this combination of options to C<::INET>
1167 when using C<::IP>, perform first a blocking connect, then afterwards turn the
1168 socket into nonblocking mode.
1170 my $sock = IO::Socket::IP->new(
1173 ) or die "Cannot connect - $@";
1175 $sock->blocking( 0 );
1177 This code will behave identically under both C<IO::Socket::INET> and
1190 Investigate whether C<POSIX::dup2> upsets BSD's C<kqueue> watchers, and if so,
1191 consider what possible workarounds might be applied.
1197 Paul Evans <leonerd@leonerd.org.uk>