2 `IO::Socket::IP' - Family-neutral IP socket supporting both IPv4 and
8 my $sock = IO::Socket::IP->new(
9 PeerHost => "www.google.com",
12 ) or die "Cannot construct socket - $@";
14 my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
15 ( $sock->sockdomain == PF_INET ) ? "IPv4" :
18 printf "Connected to google via %s\n", $familyname;
21 This module provides a protocol-independent way to use IPv4 and IPv6
22 sockets, intended as a replacement for IO::Socket::INET. Most
23 constructor arguments and methods are provided in a backward-compatible
24 way. For a list of known differences, see the `IO::Socket::INET'
25 INCOMPATIBILITES section below.
27 It uses the `getaddrinfo(3)' function to convert hostnames and service
28 names or port numbers into sets of possible addresses to connect to or
29 listen on. This allows it to work for IPv6 where the system supports it,
30 while still falling back to IPv4-only on systems which don't.
32 REPLACING `IO::Socket' DEFAULT BEHAVIOUR
33 By placing `-register' in the import list, IO::Socket uses
34 `IO::Socket::IP' rather than `IO::Socket::INET' as the class that
35 handles `PF_INET'. `IO::Socket' will also use `IO::Socket::IP' rather
36 than `IO::Socket::INET6' to handle `PF_INET6', provided that the
37 `AF_INET6' constant is available.
39 Changing `IO::Socket''s default behaviour means that calling the
40 `IO::Socket' constructor with either `PF_INET' or `PF_INET6' as the
41 `Domain' parameter will yield an `IO::Socket::IP' object.
43 use IO::Socket::IP -register;
45 my $sock = IO::Socket->new(
49 ) or die "Cannot create socket - $@\n";
51 print "Created a socket of type " . ref($sock) . "\n";
53 Note that `-register' is a global setting that applies to the entire
54 program; it cannot be applied only for certain callers, removed, or
55 limited by lexical scope.
58 $sock = IO::Socket::IP->new( %args )
59 Creates a new `IO::Socket::IP' object, containing a newly created socket
60 handle according to the named arguments passed. The recognised arguments
65 Hostname and service name for the peer to `connect()' to. The
66 service name may be given as a port number, as a decimal string.
70 For symmetry with the accessor methods and compatibility with
71 `IO::Socket::INET', these are accepted as synonyms for
72 `PeerHost' and `PeerService' respectively.
75 Alternate form of specifying the peer to `connect()' to. This
76 should be an array of the form returned by
77 `Socket::getaddrinfo'.
79 This parameter takes precedence over the `Peer*', `Family',
80 `Type' and `Proto' arguments.
83 LocalService => STRING
84 Hostname and service name for the local address to `bind()' to.
88 For symmetry with the accessor methods and compatibility with
89 `IO::Socket::INET', these are accepted as synonyms for
90 `LocalHost' and `LocalService' respectively.
92 LocalAddrInfo => ARRAY
93 Alternate form of specifying the local address to `bind()' to.
94 This should be an array of the form returned by
95 `Socket::getaddrinfo'.
97 This parameter takes precedence over the `Local*', `Family',
98 `Type' and `Proto' arguments.
101 The address family to pass to `getaddrinfo' (e.g. `AF_INET',
102 `AF_INET6'). Normally this will be left undefined, and
103 `getaddrinfo' will search using any address family supported by
107 The socket type to pass to `getaddrinfo' (e.g. `SOCK_STREAM',
108 `SOCK_DGRAM'). Normally defined by the caller; if left undefined
109 `getaddrinfo' may attempt to infer the type from the service
112 Proto => STRING or INT
113 The IP protocol to use for the socket (e.g. `'tcp'',
114 `IPPROTO_TCP', `'udp'',`IPPROTO_UDP'). Normally this will be
115 left undefined, and either `getaddrinfo' or the kernel will
116 choose an appropriate value. May be given either in string name
119 GetAddrInfoFlags => INT
120 More flags to pass to the `getaddrinfo()' function. If not
121 supplied, a default of `AI_ADDRCONFIG' will be used.
123 These flags will be combined with `AI_PASSIVE' if the `Listen'
124 argument is given. For more information see the documentation
125 about `getaddrinfo()' in the Socket module.
128 If defined, puts the socket into listening mode where new
129 connections can be accepted using the `accept' method. The value
130 given is used as the `listen(2)' queue size.
133 If true, set the `SO_REUSEADDR' sockopt
136 If true, set the `SO_REUSEPORT' sockopt (not all OSes implement
140 If true, set the `SO_BROADCAST' sockopt
143 If defined, set the `IPV6_V6ONLY' sockopt when creating
144 `PF_INET6' sockets to the given value. If true, a listening-mode
145 socket will only listen on the `AF_INET6' addresses; if false it
146 will also accept connections from `AF_INET' addresses.
148 If not defined, the socket option will not be changed, and
149 default value set by the operating system will apply. For
150 repeatable behaviour across platforms it is recommended this
151 value always be defined for listening-mode sockets.
153 Note that not all platforms support disabling this option. Some,
154 at least OpenBSD and MirBSD, will fail with `EINVAL' if you
155 attempt to disable it. To determine whether it is possible to
156 disable, you may use the class method
158 if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
165 If your platform does not support disabling this option but you
166 still want to listen for both `AF_INET' and `AF_INET6'
167 connections you will have to create two listening sockets, one
168 bound to each protocol.
171 This `IO::Socket::INET'-style argument is ignored, except if it
172 is defined but false. See the `IO::Socket::INET'
173 INCOMPATIBILITES section below.
175 However, the behaviour it enables is always performed by
179 If defined but false, the socket will be set to non-blocking
180 mode. Otherwise it will default to blocking mode. See the
181 NON-BLOCKING section below for more detail.
183 If neither `Type' nor `Proto' hints are provided, a default of
184 `SOCK_STREAM' and `IPPROTO_TCP' respectively will be set, to maintain
185 compatibility with `IO::Socket::INET'. Other named arguments that are
186 not recognised are ignored.
188 If neither `Family' nor any hosts or addresses are passed, nor any
189 `*AddrInfo', then the constructor has no information on which to decide
190 a socket family to create. In this case, it performs a `getaddinfo' call
191 with the `AI_ADDRCONFIG' flag, no host name, and a service name of
192 `"0"', and uses the family of the first returned result.
194 If the constructor fails, it will set `$@' to an appropriate error
195 message; this may be from `$!' or it may be some other string; not every
196 failure necessarily has an associated `errno' value.
198 $sock = IO::Socket::IP->new( $peeraddr )
199 As a special case, if the constructor is passed a single argument (as
200 opposed to an even-sized list of key/value pairs), it is taken to be the
201 value of the `PeerAddr' parameter. This is parsed in the same way,
202 according to the behaviour given in the `PeerHost' AND `LocalHost'
203 PARSING section below.
206 As well as the following methods, this class inherits all the methods in
207 IO::Socket and IO::Handle.
209 ( $host, $service ) = $sock->sockhost_service( $numeric )
210 Returns the hostname and service name of the local address (that is, the
211 socket address given by the `sockname' method).
213 If `$numeric' is true, these will be given in numeric form rather than
214 being resolved into names.
216 The following four convenience wrappers may be used to obtain one of the
217 two values returned here. If both host and service names are required,
218 this method is preferable to the following wrappers, because it will
219 call `getnameinfo(3)' only once.
221 $addr = $sock->sockhost
222 Return the numeric form of the local address as a textual representation
224 $port = $sock->sockport
225 Return the numeric form of the local port number
227 $host = $sock->sockhostname
228 Return the resolved name of the local address
230 $service = $sock->sockservice
231 Return the resolved name of the local port number
233 $addr = $sock->sockaddr
234 Return the local address as a binary octet string
236 ( $host, $service ) = $sock->peerhost_service( $numeric )
237 Returns the hostname and service name of the peer address (that is, the
238 socket address given by the `peername' method), similar to the
239 `sockhost_service' method.
241 The following four convenience wrappers may be used to obtain one of the
242 two values returned here. If both host and service names are required,
243 this method is preferable to the following wrappers, because it will
244 call `getnameinfo(3)' only once.
246 $addr = $sock->peerhost
247 Return the numeric form of the peer address as a textual representation
249 $port = $sock->peerport
250 Return the numeric form of the peer port number
252 $host = $sock->peerhostname
253 Return the resolved name of the peer address
255 $service = $sock->peerservice
256 Return the resolved name of the peer port number
258 $addr = $peer->peeraddr
259 Return the peer address as a binary octet string
261 $inet = $sock->as_inet
262 Returns a new IO::Socket::INET instance wrapping the same filehandle.
263 This may be useful in cases where it is required, for
264 backward-compatibility, to have a real object of `IO::Socket::INET' type
265 instead of `IO::Socket::IP'. The new object will wrap the same
266 underlying socket filehandle as the original, so care should be taken
267 not to continue to use both objects concurrently. Ideally the original
268 `$sock' should be discarded after this method is called.
270 This method checks that the socket domain is `PF_INET' and will throw an
271 exception if it isn't.
274 If the constructor is passed a defined but false value for the
275 `Blocking' argument then the socket is put into non-blocking mode. When
276 in non-blocking mode, the socket will not be set up by the time the
277 constructor returns, because the underlying `connect(2)' syscall would
278 otherwise have to block.
280 The non-blocking behaviour is an extension of the `IO::Socket::INET'
281 API, unique to `IO::Socket::IP', because the former does not support
282 multi-homed non-blocking connect.
284 When using non-blocking mode, the caller must repeatedly check for
285 writeability on the filehandle (for instance using `select' or
286 `IO::Poll'). Each time the filehandle is ready to write, the `connect'
287 method must be called, with no arguments. Note that some operating
288 systems, most notably `MSWin32' do not report a `connect()' failure
289 using write-ready; so you must also `select()' for exceptional status.
291 While `connect' returns false, the value of `$!' indicates whether it
292 should be tried again (by being set to the value `EINPROGRESS', or
293 `EWOULDBLOCK' on MSWin32), or whether a permanent error has occurred
294 (e.g. `ECONNREFUSED').
296 Once the socket has been connected to the peer, `connect' will return
297 true and the socket will now be ready to use.
299 Note that calls to the platform's underlying `getaddrinfo(3)' function
300 may block. If `IO::Socket::IP' has to perform this lookup, the
301 constructor will block even when in non-blocking mode.
303 To avoid this blocking behaviour, the caller should pass in the result
304 of such a lookup using the `PeerAddrInfo' or `LocalAddrInfo' arguments.
305 This can be achieved by using Net::LibAsyncNS, or the `getaddrinfo(3)'
306 function can be called in a child process.
309 use Errno qw( EINPROGRESS EWOULDBLOCK );
311 my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here
313 my $socket = IO::Socket::IP->new(
314 PeerAddrInfo => \@peeraddrinfo,
316 ) or die "Cannot construct socket - $@";
318 while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
320 vec( $wvec, fileno $socket, 1 ) = 1;
322 vec( $evec, fileno $socket, 1 ) = 1;
324 select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
327 die "Cannot connect - $!" if $!;
331 The example above uses `select()', but any similar mechanism should work
332 analogously. `IO::Socket::IP' takes care when creating new socket
333 filehandles to preserve the actual file descriptor number, so such
334 techniques as `poll' or `epoll' should be transparent to its
335 reallocation of a different socket underneath, perhaps in order to
336 switch protocol family between `PF_INET' and `PF_INET6'.
338 For another example using `IO::Poll' and `Net::LibAsyncNS', see the
339 examples/nonblocking_libasyncns.pl file in the module distribution.
341 `PeerHost' AND `LocalHost' PARSING
342 To support the `IO::Socket::INET' API, the host and port information may
343 be passed in a single string rather than as two separate arguments.
345 If either `LocalHost' or `PeerHost' (or their `...Addr' synonyms) have
346 any of the following special forms then special parsing is applied.
348 The value of the `...Host' argument will be split to give both the
349 hostname and port (or service name):
351 hostname.example.org:http # Host name
352 192.0.2.1:80 # IPv4 address
353 [2001:db8::1]:80 # IPv6 address
355 In each case, the port or service name (e.g. `80') is passed as the
356 `LocalService' or `PeerService' argument.
358 Either of `LocalService' or `PeerService' (or their `...Port' synonyms)
359 can be either a service name, a decimal number, or a string containing
360 both a service name and number, in a form such as
364 In this case, the name (`http') will be tried first, but if the resolver
365 does not understand it then the port number (`80') will be used instead.
367 If the `...Host' argument is in this special form and the corresponding
368 `...Service' or `...Port' argument is also defined, the one parsed from
369 the `...Host' argument will take precedence and the other will be
372 ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
373 Utility method that provides the parsing functionality described above.
374 Returns a 2-element list, containing either the split hostname and port
375 description if it could be parsed, or the given address and `undef' if
376 it was not recognised.
378 IO::Socket::IP->split_addr( "hostname:http" )
379 # ( "hostname", "http" )
381 IO::Socket::IP->split_addr( "192.0.2.1:80" )
382 # ( "192.0.2.1", "80" )
384 IO::Socket::IP->split_addr( "[2001:db8::1]:80" )
385 # ( "2001:db8::1", "80" )
387 IO::Socket::IP->split_addr( "something.else" )
388 # ( "something.else", undef )
390 $addr = IO::Socket::IP->join_addr( $host, $port )
391 Utility method that performs the reverse of `split_addr', returning a
392 string formed by joining the specified host address and port number. The
393 host address will be wrapped in `[]' brackets if required (because it is
394 a raw IPv6 numeric address).
396 This can be especially useful when combined with the `sockhost_service'
397 or `peerhost_service' methods.
399 say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
401 `IO::Socket::INET' INCOMPATIBILITES
402 * The behaviour enabled by `MultiHomed' is in fact implemented by
403 `IO::Socket::IP' as it is required to correctly support searching
404 for a useable address from the results of the `getaddrinfo(3)' call.
405 The constructor will ignore the value of this argument, except if it
406 is defined but false. An exception is thrown in this case, because
407 that would request it disable the `getaddrinfo(3)' search behaviour
411 * Investigate whether `POSIX::dup2' upsets BSD's `kqueue' watchers,
412 and if so, consider what possible workarounds might be applied.
415 Paul Evans <leonerd@leonerd.org.uk>