Codex

IO::Socket::IP

Section: User Contributed Perl Documentation (3pm)

Updated: 2014-09-14

Index?action=index Return to Main Contents


NAME

"IO::Socket::IP" - Family-neutral IP socket supporting both IPv4 and IPv6

SYNOPSIS

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;

@]

DESCRIPTION

This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement for IO::Socket::INET. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see the INCOMPATIBILITES section below.
It uses the 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.

REPLACING IO::Socket DEFAULT BEHAVIOUR

By placing in the import list, IO::Socket uses rather than as the class that handles . will also use rather than to handle , provided that the constant is available.
Changing 's default behaviour means that calling the constructor with either or as the parameter will yield an object.
Note that is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope.

CONSTRUCTORS

$sock = IO::Socket::IP->new( %args )

Creates a new object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are:

:PeerHost => STRING

PeerService => STRING
Hostname and service name for the peer to to. The service name may be given as a port number, as a decimal string.:

:PeerAddr => STRING

PeerPort => STRING
For symmetry with the accessor methods and compatibility with , these are accepted as synonyms for and respectively.:
PeerAddrInfo => ARRAY
Alternate form of specifying the peer to to. This should be an array of the form returned by .
This parameter takes precedence over the , , and arguments.

:

:LocalHost => STRING

LocalService => STRING
Hostname and service name for the local address to to.:

:LocalAddr => STRING

LocalPort => STRING
For symmetry with the accessor methods and compatibility with , these are accepted as synonyms for and respectively.:
LocalAddrInfo => ARRAY
Alternate form of specifying the local address to to. This should be an array of the form returned by .
This parameter takes precedence over the , , and arguments.

:

Family => INT
The address family to pass to (e.g. , ). Normally this will be left undefined, and will search using any address family supported by the system.:
Type => INT
The socket type to pass to (e.g. , ). Normally defined by the caller; if left undefined may attempt to infer the type from the service name.:
Proto => STRING or INT
The IP protocol to use for the socket (e.g. , , , ). Normally this will be left undefined, and either or the kernel will choose an appropriate value. May be given either in string name or numeric form.:
GetAddrInfoFlags => INT
More flags to pass to the function. If not supplied, a default of will be used.
These flags will be combined with if the argument is given. For more information see the documentation about in the Socket module.

:

Listen => INT
If defined, puts the socket into listening mode where new connections can be accepted using the method. The value given is used as the queue size.:
ReuseAddr => BOOL
If true, set the sockopt:
ReusePort => BOOL
If true, set the sockopt (not all OSes implement this sockopt):
Broadcast => BOOL
If true, set the sockopt:
V6Only => BOOL
If defined, set the sockopt when creating sockets to the given value. If true, a listening-mode socket will only listen on the addresses; if false it will also accept connections from 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 if you attempt to disable it. To determine whether it is possible to disable, you may use the class method
If your platform does not support disabling this option but you still want to listen for both and connections you will have to create two listening sockets, one bound to each protocol.

:

MultiHomed
This -style argument is ignored, except if it is defined but false. See the INCOMPATIBILITES section below.
However, the behaviour it enables is always performed by .

:

Blocking => 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.:
Timeout => NUM
If defined, gives a maximum time in seconds to block per 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 ; for more fine grained control over connection timeouts, consider performing a nonblocking connect directly.

:

If neither nor hints are provided, a default of and respectively will be set, to maintain compatibility with . Other named arguments that are not recognised are ignored.
If neither nor any hosts or addresses are passed, nor any , then the constructor has no information on which to decide a socket family to create. In this case, it performs a call with the flag, no host name, and a service name of , 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 associated value.

$sock = IO::Socket::IP->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 parameter. This is parsed in the same way, according to the behaviour given in the AND PARSING section below.

METHODS

As well as the following methods, this class inherits all the methods in IO::Socket and IO::Handle.

( $host, $service ) = $sock->sockhost_service( $numeric )

Returns the hostname and service name of the local address (that is, the socket address given by the method).
If 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 only once.

$addr = $sock->sockhost

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

$port = $sock->sockport

Return the numeric form of the local port number

$host = $sock->sockhostname

Return the resolved name of the local address

$service = $sock->sockservice

Return the resolved name of the local port number

$addr = $sock->sockaddr

Return the local address as a binary octet string

( $host, $service ) = $sock->peerhost_service( $numeric )

Returns the hostname and service name of the peer address (that is, the socket address given by the method), similar to the 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 only once.

$addr = $sock->peerhost

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

$port = $sock->peerport

Return the numeric form of the peer port number

$host = $sock->peerhostname

Return the resolved name of the peer address

$service = $sock->peerservice

Return the resolved name of the peer port number

$addr = $peer->peeraddr

Return the peer address as a binary octet string

$inet = $sock->as_inet

Returns a new IO::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 of type instead of . 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 should be discarded after this method is called.
This method checks that the socket domain is and will throw an exception if it isn't.

NON-BLOCKING

If the constructor is passed a defined but false value for the 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 syscall would otherwise have to block.
The non-blocking behaviour is an extension of the API, unique to , 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 or ). Each time the filehandle is ready to write, the method must be called, with no arguments. Note that some operating systems, most notably do not report a failure using write-ready; so you must also for exceptional status.
While returns false, the value of indicates whether it should be tried again (by being set to the value , or on MSWin32), or whether a permanent error has occurred (e.g. ).
Once the socket has been connected to the peer, will return true and the socket will now be ready to use.
Note that calls to the platform's underlying function may block. If 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 or arguments. This can be achieved by using Net::LibAsyncNS, or the function can be called in a child process.
The example above uses , but any similar mechanism should work analogously. takes care when creating new socket filehandles to preserve the actual file descriptor number, so such techniques as or should be transparent to its reallocation of a different socket underneath, perhaps in order to switch protocol family between and .
For another example using and , see the examples/nonblocking_libasyncns.pl file in the module distribution.

PeerHost AND LocalHost PARSING

To support the API, the host and port information may be passed in a single string rather than as two separate arguments.
If either or (or their synonyms) have any of the following special forms then special parsing is applied.
The value of the argument will be split to give both the hostname and port (or service name):
In each case, the port or service name (e.g. ) is passed as the or argument.
Either of or (or their 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
In this case, the name ( ) will be tried first, but if the resolver does not understand it then the port number ( ) will be used instead.
If the argument is in this special form and the corresponding or argument is also defined, the one parsed from the argument will take precedence and the other will be ignored.

( $host, $port ) = IO::Socket::IP->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 if it was not recognised.

$addr = IO::Socket::IP->join_addr( $host, $port )

Utility method that performs the reverse of , 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 the or methods.

IO::Socket::INET INCOMPATIBILITES

The behaviour enabled by is in fact implemented by as it is required to correctly support searching for a useable address from the results of the 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 search behaviour in the first place.:
implements both the and parameters, but it implements the interaction of both in a different way.
In , supplying a timeout overrides the non-blocking behaviour, meaning that the 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 therefore, the parameter takes precedence - if a non-blocking socket is requested, no operation will block. The parameter here simply defines the maximum time that a blocking 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 when using , perform first a blocking connect, then afterwards turn the socket into nonblocking mode.
This code will behave identically under both and .

:

TODO

Investigate whether upsets BSD's watchers, and if so, consider what possible workarounds might be applied.:

AUTHOR

Paul Evans <[email protected]>


Index

NAME

SYNOPSIS

DESCRIPTION

REPLACING IO::Socket DEFAULT BEHAVIOUR

CONSTRUCTORS

$sock = IO::Socket::IP->new( %args )

$sock = IO::Socket::IP->new( $peeraddr )

METHODS

( $host, $service ) = $sock->sockhost_service( $numeric )

$addr = $sock->sockhost

$port = $sock->sockport

$host = $sock->sockhostname

$service = $sock->sockservice

$addr = $sock->sockaddr

( $host, $service ) = $sock->peerhost_service( $numeric )

$addr = $sock->peerhost

$port = $sock->peerport

$host = $sock->peerhostname

$service = $sock->peerservice

$addr = $peer->peeraddr

$inet = $sock->as_inet

NON-BLOCKING

PeerHost AND LocalHost PARSING

( $host, $port ) = IO::Socket::IP->split_addr( $addr )

$addr = IO::Socket::IP->join_addr( $host, $port )

IO::Socket::INET INCOMPATIBILITES

TODO

AUTHOR