IO::Socket::IP
- Family-neutral IP socket supporting both IPv4 and IPv6
use IO::Socket::IP;my $sock = IO::Socket::IP->new( PeerHost => "www.google.com", PeerPort => "http", Type => SOCK_STREAM,) or die "Cannot construct socket - $@";my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" : ( $sock->sockdomain == PF_INET ) ? "IPv4" : "unknown";printf "Connected to google via %s\n", $familyname;
This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement forIO::Socket::INET. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see theIO::Socket::INET
INCOMPATIBILITES section below.
It uses thegetaddrinfo(3)
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.
IO::Socket
DEFAULT BEHAVIOURBy placing-register
in the import list,IO::Socket usesIO::Socket::IP
rather thanIO::Socket::INET
as the class that handlesPF_INET
.IO::Socket
will also useIO::Socket::IP
rather thanIO::Socket::INET6
to handlePF_INET6
, provided that theAF_INET6
constant is available.
ChangingIO::Socket
's default behaviour means that calling theIO::Socket
constructor with eitherPF_INET
orPF_INET6
as theDomain
parameter will yield anIO::Socket::IP
object.
use IO::Socket::IP -register;my $sock = IO::Socket->new( Domain => PF_INET6, LocalHost => "::1", Listen => 1,) or die "Cannot create socket - $@\n";print "Created a socket of type " . ref($sock) . "\n";
Note that-register
is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope.
Creates a newIO::Socket::IP
object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are:
Hostname and service name for the peer toconnect()
to. The service name may be given as a port number, as a decimal string.
For symmetry with the accessor methods and compatibility withIO::Socket::INET
, these are accepted as synonyms forPeerHost
andPeerService
respectively.
Alternate form of specifying the peer toconnect()
to. This should be an array of the form returned bySocket::getaddrinfo
.
This parameter takes precedence over thePeer*
,Family
,Type
andProto
arguments.
Hostname and service name for the local address tobind()
to.
For symmetry with the accessor methods and compatibility withIO::Socket::INET
, these are accepted as synonyms forLocalHost
andLocalService
respectively.
Alternate form of specifying the local address tobind()
to. This should be an array of the form returned bySocket::getaddrinfo
.
This parameter takes precedence over theLocal*
,Family
,Type
andProto
arguments.
The address family to pass togetaddrinfo
(e.g.AF_INET
,AF_INET6
). Normally this will be left undefined, andgetaddrinfo
will search using any address family supported by the system.
The socket type to pass togetaddrinfo
(e.g.SOCK_STREAM
,SOCK_DGRAM
). Normally defined by the caller; if left undefinedgetaddrinfo
may attempt to infer the type from the service name.
The IP protocol to use for the socket (e.g.'tcp'
,IPPROTO_TCP
,'udp'
,IPPROTO_UDP
). Normally this will be left undefined, and eithergetaddrinfo
or the kernel will choose an appropriate value. May be given either in string name or numeric form.
More flags to pass to thegetaddrinfo()
function. If not supplied, a default ofAI_ADDRCONFIG
will be used.
These flags will be combined withAI_PASSIVE
if theListen
argument is given. For more information see the documentation aboutgetaddrinfo()
in theSocket module.
If defined, puts the socket into listening mode where new connections can be accepted using theaccept
method. The value given is used as thelisten(2)
queue size.
If true, set theSO_REUSEADDR
sockopt
If true, set theSO_REUSEPORT
sockopt (not all OSes implement this sockopt)
If true, set theSO_BROADCAST
sockopt
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 settingReuseAddr
.
Sockopts => [ [ SOL_SOCKET, SO_REUSEADDR ], [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],]
If defined, set theIPV6_V6ONLY
sockopt when creatingPF_INET6
sockets to the given value. If true, a listening-mode socket will only listen on theAF_INET6
addresses; if false it will also accept connections fromAF_INET
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 withEINVAL
if you attempt to disable it. To determine whether it is possible to disable, you may use the class method
if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) { ...}else { ...}
If your platform does not support disabling this option but you still want to listen for bothAF_INET
andAF_INET6
connections you will have to create two listening sockets, one bound to each protocol.
ThisIO::Socket::INET
-style argument is ignored, except if it is defined but false. See theIO::Socket::INET
INCOMPATIBILITES section below.
However, the behaviour it enables is always performed byIO::Socket::IP
.
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.
If defined, gives a maximum time in seconds to block perconnect()
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 byIO::Socket::INET
; for more fine grained control over connection timeouts, consider performing a nonblocking connect directly.
If neitherType
norProto
hints are provided, a default ofSOCK_STREAM
andIPPROTO_TCP
respectively will be set, to maintain compatibility withIO::Socket::INET
. Other named arguments that are not recognised are ignored.
If neitherFamily
nor any hosts or addresses are passed, nor any*AddrInfo
, then the constructor has no information on which to decide a socket family to create. In this case, it performs agetaddinfo
call with theAI_ADDRCONFIG
flag, no host name, and a service name of"0"
, and uses the family of the first returned result.
If the constructor fails, it will set$@
to an appropriate error message; this may be from$!
or it may be some other string; not every failure necessarily has an associatederrno
value.
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 thePeerAddr
parameter. This is parsed in the same way, according to the behaviour given in thePeerHost
ANDLocalHost
PARSING section below.
As well as the following methods, this class inherits all the methods inIO::Socket andIO::Handle.
Returns the hostname and service name of the local address (that is, the socket address given by thesockname
method).
If$numeric
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 callgetnameinfo(3)
only once.
Return the numeric form of the local address as a textual representation
Return the numeric form of the local port number
Return the resolved name of the local address
Return the resolved name of the local port number
Return the local address as a binary octet string
Returns the hostname and service name of the peer address (that is, the socket address given by thepeername
method), similar to thesockhost_service
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 callgetnameinfo(3)
only once.
Return the numeric form of the peer address as a textual representation
Return the numeric form of the peer port number
Return the resolved name of the peer address
Return the resolved name of the peer port number
Return the peer address as a binary octet string
Returns a newIO::Socket::INET instance wrapping the same filehandle. This may be useful in cases where it is required, for backward-compatibility, to have a real object ofIO::Socket::INET
type instead ofIO::Socket::IP
. 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$sock
should be discarded after this method is called.
This method checks that the socket domain isPF_INET
and will throw an exception if it isn't.
If the constructor is passed a defined but false value for theBlocking
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 underlyingconnect(2)
syscall would otherwise have to block.
The non-blocking behaviour is an extension of theIO::Socket::INET
API, unique toIO::Socket::IP
, 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 usingselect
orIO::Poll
). Each time the filehandle is ready to write, theconnect
method must be called, with no arguments. Note that some operating systems, most notablyMSWin32
do not report aconnect()
failure using write-ready; so you must alsoselect()
for exceptional status.
Whileconnect
returns false, the value of$!
indicates whether it should be tried again (by being set to the valueEINPROGRESS
, orEWOULDBLOCK
on MSWin32), or whether a permanent error has occurred (e.g.ECONNREFUSED
).
Once the socket has been connected to the peer,connect
will return true and the socket will now be ready to use.
Note that calls to the platform's underlyinggetaddrinfo(3)
function may block. IfIO::Socket::IP
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 thePeerAddrInfo
orLocalAddrInfo
arguments. This can be achieved by usingNet::LibAsyncNS, or thegetaddrinfo(3)
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 heremy $socket = IO::Socket::IP->new( PeerAddrInfo => \@peeraddrinfo, Blocking => 0,) or die "Cannot construct socket - $@";while( !$socket->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 usesselect()
, but any similar mechanism should work analogously.IO::Socket::IP
takes care when creating new socket filehandles to preserve the actual file descriptor number, so such techniques aspoll
orepoll
should be transparent to its reallocation of a different socket underneath, perhaps in order to switch protocol family betweenPF_INET
andPF_INET6
.
For another example usingIO::Poll
andNet::LibAsyncNS
, see theexamples/nonblocking_libasyncns.pl file in the module distribution.
PeerHost
ANDLocalHost
PARSINGTo support theIO::Socket::INET
API, the host and port information may be passed in a single string rather than as two separate arguments.
If eitherLocalHost
orPeerHost
(or their...Addr
synonyms) have any of the following special forms then special parsing is applied.
The value of the...Host
argument will be split to give both the hostname and port (or service name):
hostname.example.org:http # Host name192.0.2.1:80 # IPv4 address[2001:db8::1]:80 # IPv6 address
In each case, the port or service name (e.g.80
) is passed as theLocalService
orPeerService
argument.
Either ofLocalService
orPeerService
(or their...Port
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 (http
) will be tried first, but if the resolver does not understand it then the port number (80
) will be used instead.
If the...Host
argument is in this special form and the corresponding...Service
or...Port
argument is also defined, the one parsed from the...Host
argument will take precedence and the other will be ignored.
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 andundef
if it was not recognised.
IO::Socket::IP->split_addr( "hostname:http" ) # ( "hostname", "http" )IO::Socket::IP->split_addr( "192.0.2.1:80" ) # ( "192.0.2.1", "80" )IO::Socket::IP->split_addr( "[2001:db8::1]:80" ) # ( "2001:db8::1", "80" )IO::Socket::IP->split_addr( "something.else" ) # ( "something.else", undef )
Utility method that performs the reverse ofsplit_addr
, returning a string formed by joining the specified host address and port number. The host address will be wrapped in[]
brackets if required (because it is a raw IPv6 numeric address).
This can be especially useful when combined with thesockhost_service
orpeerhost_service
methods.
say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
IO::Socket::INET
INCOMPATIBILITESThe behaviour enabled byMultiHomed
is in fact implemented byIO::Socket::IP
as it is required to correctly support searching for a useable address from the results of thegetaddrinfo(3)
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 thegetaddrinfo(3)
search behaviour in the first place.
IO::Socket::IP
implements both theBlocking
andTimeout
parameters, but it implements the interaction of both in a different way.
In::INET
, supplying a timeout overrides the non-blocking behaviour, meaning that theconnect()
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::IP
therefore, theBlocking
parameter takes precedence - if a non-blocking socket is requested, no operation will block. TheTimeout
parameter here simply defines the maximum time that a blockingconnect()
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::INET
when using::IP
, perform first a blocking connect, then afterwards turn the socket into nonblocking mode.
my $sock = IO::Socket::IP->new( PeerHost => $peer, Timeout => 20,) or die "Cannot connect - $@";$sock->blocking( 0 );
This code will behave identically under bothIO::Socket::INET
andIO::Socket::IP
.
Investigate whetherPOSIX::dup2
upsets BSD'skqueue
watchers, and if so, consider what possible workarounds might be applied.
Paul Evans <leonerd@leonerd.org.uk>
Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.
The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.