1IO::Socket::IP(3)     User Contributed Perl Documentation    IO::Socket::IP(3)
2
3
4

NAME

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

SYNOPSIS

10        use IO::Socket::IP;
11
12        my $sock = IO::Socket::IP->new(
13           PeerHost => "www.google.com",
14           PeerPort => "http",
15           Type     => SOCK_STREAM,
16        ) or die "Cannot construct socket - $@";
17
18        my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
19                         ( $sock->sockdomain == PF_INET  ) ? "IPv4" :
20                                                             "unknown";
21
22        printf "Connected to google via %s\n", $familyname;
23

DESCRIPTION

25       This module provides a protocol-independent way to use IPv4 and IPv6
26       sockets, intended as a replacement for IO::Socket::INET. Most
27       constructor arguments and methods are provided in a backward-compatible
28       way. For a list of known differences, see the "IO::Socket::INET"
29       INCOMPATIBILITES section below.
30
31       It uses the getaddrinfo(3) function to convert hostnames and service
32       names or port numbers into sets of possible addresses to connect to or
33       listen on.  This allows it to work for IPv6 where the system supports
34       it, while still falling back to IPv4-only on systems which don't.
35

REPLACING "IO::Socket" DEFAULT BEHAVIOUR

37       By placing "-register" in the import list to "IO::Socket::IP", it will
38       register itself with IO::Socket as the class that handles "PF_INET". It
39       will also ask to handle "PF_INET6" as well, provided that constant is
40       available.
41
42       Changing "IO::Socket"'s default behaviour means that calling the
43       "IO::Socket" constructor with either "PF_INET" or "PF_INET6" as the
44       "Domain" parameter will yield an "IO::Socket::IP" object.
45
46        use IO::Socket::IP -register;
47
48        my $sock = IO::Socket->new(
49           Domain    => PF_INET6,
50           LocalHost => "::1",
51           Listen    => 1,
52        ) or die "Cannot create socket - $@\n";
53
54        print "Created a socket of type " . ref($sock) . "\n";
55
56       Note that "-register" is a global setting that applies to the entire
57       program; it cannot be applied only for certain callers, removed, or
58       limited by lexical scope.
59

CONSTRUCTORS

61   new
62          $sock = IO::Socket::IP->new( %args )
63
64       Creates a new "IO::Socket::IP" object, containing a newly created
65       socket handle according to the named arguments passed. The recognised
66       arguments are:
67
68       PeerHost => STRING
69       PeerService => STRING
70               Hostname and service name for the peer to "connect()" to. The
71               service name may be given as a port number, as a decimal
72               string.
73
74       PeerAddr => STRING
75       PeerPort => STRING
76               For symmetry with the accessor methods and compatibility with
77               "IO::Socket::INET", these are accepted as synonyms for
78               "PeerHost" and "PeerService" respectively.
79
80       PeerAddrInfo => ARRAY
81               Alternate form of specifying the peer to "connect()" to. This
82               should be an array of the form returned by
83               "Socket::getaddrinfo".
84
85               This parameter takes precedence over the "Peer*", "Family",
86               "Type" and "Proto" arguments.
87
88       LocalHost => STRING
89       LocalService => STRING
90               Hostname and service name for the local address to "bind()" to.
91
92       LocalAddr => STRING
93       LocalPort => STRING
94               For symmetry with the accessor methods and compatibility with
95               "IO::Socket::INET", these are accepted as synonyms for
96               "LocalHost" and "LocalService" respectively.
97
98       LocalAddrInfo => ARRAY
99               Alternate form of specifying the local address to "bind()" to.
100               This should be an array of the form returned by
101               "Socket::getaddrinfo".
102
103               This parameter takes precedence over the "Local*", "Family",
104               "Type" and "Proto" arguments.
105
106       Family => INT
107               The address family to pass to "getaddrinfo" (e.g. "AF_INET",
108               "AF_INET6").  Normally this will be left undefined, and
109               "getaddrinfo" will search using any address family supported by
110               the system.
111
112       Type => INT
113               The socket type to pass to "getaddrinfo" (e.g. "SOCK_STREAM",
114               "SOCK_DGRAM"). Normally defined by the caller; if left
115               undefined "getaddrinfo" may attempt to infer the type from the
116               service name.
117
118       Proto => STRING or INT
119               The IP protocol to use for the socket (e.g. 'tcp',
120               "IPPROTO_TCP", 'udp',"IPPROTO_UDP"). Normally this will be left
121               undefined, and either "getaddrinfo" or the kernel will choose
122               an appropriate value. May be given either in string name or
123               numeric form.
124
125       GetAddrInfoFlags => INT
126               More flags to pass to the "getaddrinfo()" function. If not
127               supplied, a default of "AI_ADDRCONFIG" will be used.
128
129               These flags will be combined with "AI_PASSIVE" if the "Listen"
130               argument is given. For more information see the documentation
131               about "getaddrinfo()" in the Socket module.
132
133       Listen => INT
134               If defined, puts the socket into listening mode where new
135               connections can be accepted using the "accept" method. The
136               value given is used as the listen(2) queue size.
137
138       ReuseAddr => BOOL
139               If true, set the "SO_REUSEADDR" sockopt
140
141       ReusePort => BOOL
142               If true, set the "SO_REUSEPORT" sockopt (not all OSes implement
143               this sockopt)
144
145       Broadcast => BOOL
146               If true, set the "SO_BROADCAST" sockopt
147
148       Sockopts => ARRAY
149               An optional array of other socket options to apply after the
150               three listed above. The value is an ARRAY containing 2- or
151               3-element ARRAYrefs. Each inner array relates to a single
152               option, giving the level and option name, and an optional
153               value. If the value element is missing, it will be given the
154               value of a platform-sized integer 1 constant (i.e. suitable to
155               enable most of the common boolean options).
156
157               For example, both options given below are equivalent to setting
158               "ReuseAddr".
159
160                Sockopts => [
161                   [ SOL_SOCKET, SO_REUSEADDR ],
162                   [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],
163                ]
164
165       V6Only => BOOL
166               If defined, set the "IPV6_V6ONLY" sockopt when creating
167               "PF_INET6" sockets to the given value. If true, a listening-
168               mode socket will only listen on the "AF_INET6" addresses; if
169               false it will also accept connections from "AF_INET" addresses.
170
171               If not defined, the socket option will not be changed, and
172               default value set by the operating system will apply. For
173               repeatable behaviour across platforms it is recommended this
174               value always be defined for listening-mode sockets.
175
176               Note that not all platforms support disabling this option.
177               Some, at least OpenBSD and MirBSD, will fail with "EINVAL" if
178               you attempt to disable it.  To determine whether it is possible
179               to disable, you may use the class method
180
181                if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
182                   ...
183                }
184                else {
185                   ...
186                }
187
188               If your platform does not support disabling this option but you
189               still want to listen for both "AF_INET" and "AF_INET6"
190               connections you will have to create two listening sockets, one
191               bound to each protocol.
192
193       MultiHomed
194               This "IO::Socket::INET"-style argument is ignored, except if it
195               is defined but false. See the "IO::Socket::INET"
196               INCOMPATIBILITES section below.
197
198               However, the behaviour it enables is always performed by
199               "IO::Socket::IP".
200
201       Blocking => BOOL
202               If defined but false, the socket will be set to non-blocking
203               mode. Otherwise it will default to blocking mode. See the NON-
204               BLOCKING section below for more detail.
205
206       Timeout => NUM
207               If defined, gives a maximum time in seconds to block per
208               "connect()" call when in blocking mode. If missing, no timeout
209               is applied other than that provided by the underlying operating
210               system. When in non-blocking mode this parameter is ignored.
211
212               Note that if the hostname resolves to multiple address
213               candidates, the same timeout will apply to each connection
214               attempt individually, rather than to the operation as a whole.
215               Further note that the timeout does not apply to the initial
216               hostname resolve operation, if connecting by hostname.
217
218               This behviour is copied inspired by "IO::Socket::INET"; for
219               more fine grained control over connection timeouts, consider
220               performing a nonblocking connect directly.
221
222       If neither "Type" nor "Proto" hints are provided, a default of
223       "SOCK_STREAM" and "IPPROTO_TCP" respectively will be set, to maintain
224       compatibility with "IO::Socket::INET". Other named arguments that are
225       not recognised are ignored.
226
227       If neither "Family" nor any hosts or addresses are passed, nor any
228       *AddrInfo, then the constructor has no information on which to decide a
229       socket family to create. In this case, it performs a "getaddinfo" call
230       with the "AI_ADDRCONFIG" flag, no host name, and a service name of "0",
231       and uses the family of the first returned result.
232
233       If the constructor fails, it will set $@ to an appropriate error
234       message; this may be from $! or it may be some other string; not every
235       failure necessarily has an associated "errno" value.
236
237   new (one arg)
238          $sock = IO::Socket::IP->new( $peeraddr )
239
240       As a special case, if the constructor is passed a single argument (as
241       opposed to an even-sized list of key/value pairs), it is taken to be
242       the value of the "PeerAddr" parameter. This is parsed in the same way,
243       according to the behaviour given in the "PeerHost" AND "LocalHost"
244       PARSING section below.
245

METHODS

247       As well as the following methods, this class inherits all the methods
248       in IO::Socket and IO::Handle.
249
250   sockhost_service
251          ( $host, $service ) = $sock->sockhost_service( $numeric )
252
253       Returns the hostname and service name of the local address (that is,
254       the socket address given by the "sockname" method).
255
256       If $numeric is true, these will be given in numeric form rather than
257       being resolved into names.
258
259       The following four convenience wrappers may be used to obtain one of
260       the two values returned here. If both host and service names are
261       required, this method is preferable to the following wrappers, because
262       it will call getnameinfo(3) only once.
263
264   sockhost
265          $addr = $sock->sockhost
266
267       Return the numeric form of the local address as a textual
268       representation
269
270   sockport
271          $port = $sock->sockport
272
273       Return the numeric form of the local port number
274
275   sockhostname
276          $host = $sock->sockhostname
277
278       Return the resolved name of the local address
279
280   sockservice
281          $service = $sock->sockservice
282
283       Return the resolved name of the local port number
284
285   sockaddr
286          $addr = $sock->sockaddr
287
288       Return the local address as a binary octet string
289
290   peerhost_service
291          ( $host, $service ) = $sock->peerhost_service( $numeric )
292
293       Returns the hostname and service name of the peer address (that is, the
294       socket address given by the "peername" method), similar to the
295       "sockhost_service" method.
296
297       The following four convenience wrappers may be used to obtain one of
298       the two values returned here. If both host and service names are
299       required, this method is preferable to the following wrappers, because
300       it will call getnameinfo(3) only once.
301
302   peerhost
303          $addr = $sock->peerhost
304
305       Return the numeric form of the peer address as a textual representation
306
307   peerport
308          $port = $sock->peerport
309
310       Return the numeric form of the peer port number
311
312   peerhostname
313          $host = $sock->peerhostname
314
315       Return the resolved name of the peer address
316
317   peerservice
318          $service = $sock->peerservice
319
320       Return the resolved name of the peer port number
321
322   peeraddr
323          $addr = $peer->peeraddr
324
325       Return the peer address as a binary octet string
326
327   as_inet
328          $inet = $sock->as_inet
329
330       Returns a new IO::Socket::INET instance wrapping the same filehandle.
331       This may be useful in cases where it is required, for backward-
332       compatibility, to have a real object of "IO::Socket::INET" type instead
333       of "IO::Socket::IP".  The new object will wrap the same underlying
334       socket filehandle as the original, so care should be taken not to
335       continue to use both objects concurrently. Ideally the original $sock
336       should be discarded after this method is called.
337
338       This method checks that the socket domain is "PF_INET" and will throw
339       an exception if it isn't.
340

NON-BLOCKING

342       If the constructor is passed a defined but false value for the
343       "Blocking" argument then the socket is put into non-blocking mode. When
344       in non-blocking mode, the socket will not be set up by the time the
345       constructor returns, because the underlying connect(2) syscall would
346       otherwise have to block.
347
348       The non-blocking behaviour is an extension of the "IO::Socket::INET"
349       API, unique to "IO::Socket::IP", because the former does not support
350       multi-homed non-blocking connect.
351
352       When using non-blocking mode, the caller must repeatedly check for
353       writeability on the filehandle (for instance using "select" or
354       "IO::Poll").  Each time the filehandle is ready to write, the "connect"
355       method must be called, with no arguments. Note that some operating
356       systems, most notably "MSWin32" do not report a "connect()" failure
357       using write-ready; so you must also "select()" for exceptional status.
358
359       While "connect" returns false, the value of $! indicates whether it
360       should be tried again (by being set to the value "EINPROGRESS", or
361       "EWOULDBLOCK" on MSWin32), or whether a permanent error has occurred
362       (e.g. "ECONNREFUSED").
363
364       Once the socket has been connected to the peer, "connect" will return
365       true and the socket will now be ready to use.
366
367       Note that calls to the platform's underlying getaddrinfo(3) function
368       may block. If "IO::Socket::IP" has to perform this lookup, the
369       constructor will block even when in non-blocking mode.
370
371       To avoid this blocking behaviour, the caller should pass in the result
372       of such a lookup using the "PeerAddrInfo" or "LocalAddrInfo" arguments.
373       This can be achieved by using Net::LibAsyncNS, or the getaddrinfo(3)
374       function can be called in a child process.
375
376        use IO::Socket::IP;
377        use Errno qw( EINPROGRESS EWOULDBLOCK );
378
379        my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here
380
381        my $socket = IO::Socket::IP->new(
382           PeerAddrInfo => \@peeraddrinfo,
383           Blocking     => 0,
384        ) or die "Cannot construct socket - $@";
385
386        while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
387           my $wvec = '';
388           vec( $wvec, fileno $socket, 1 ) = 1;
389           my $evec = '';
390           vec( $evec, fileno $socket, 1 ) = 1;
391
392           select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
393        }
394
395        die "Cannot connect - $!" if $!;
396
397        ...
398
399       The example above uses "select()", but any similar mechanism should
400       work analogously. "IO::Socket::IP" takes care when creating new socket
401       filehandles to preserve the actual file descriptor number, so such
402       techniques as "poll" or "epoll" should be transparent to its
403       reallocation of a different socket underneath, perhaps in order to
404       switch protocol family between "PF_INET" and "PF_INET6".
405
406       For another example using "IO::Poll" and "Net::LibAsyncNS", see the
407       examples/nonblocking_libasyncns.pl file in the module distribution.
408

"PeerHost" AND "LocalHost" PARSING

410       To support the "IO::Socket::INET" API, the host and port information
411       may be passed in a single string rather than as two separate arguments.
412
413       If either "LocalHost" or "PeerHost" (or their "...Addr" synonyms) have
414       any of the following special forms then special parsing is applied.
415
416       The value of the "...Host" argument will be split to give both the
417       hostname and port (or service name):
418
419        hostname.example.org:http    # Host name
420        192.0.2.1:80                 # IPv4 address
421        [2001:db8::1]:80             # IPv6 address
422
423       In each case, the port or service name (e.g. 80) is passed as the
424       "LocalService" or "PeerService" argument.
425
426       Either of "LocalService" or "PeerService" (or their "...Port" synonyms)
427       can be either a service name, a decimal number, or a string containing
428       both a service name and number, in a form such as
429
430        http(80)
431
432       In this case, the name ("http") will be tried first, but if the
433       resolver does not understand it then the port number (80) will be used
434       instead.
435
436       If the "...Host" argument is in this special form and the corresponding
437       "...Service" or "...Port" argument is also defined, the one parsed from
438       the "...Host" argument will take precedence and the other will be
439       ignored.
440
441   split_addr
442          ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
443
444       Utility method that provides the parsing functionality described above.
445       Returns a 2-element list, containing either the split hostname and port
446       description if it could be parsed, or the given address and "undef" if
447       it was not recognised.
448
449        IO::Socket::IP->split_addr( "hostname:http" )
450                                     # ( "hostname",  "http" )
451
452        IO::Socket::IP->split_addr( "192.0.2.1:80" )
453                                     # ( "192.0.2.1", "80"   )
454
455        IO::Socket::IP->split_addr( "[2001:db8::1]:80" )
456                                     # ( "2001:db8::1", "80" )
457
458        IO::Socket::IP->split_addr( "something.else" )
459                                     # ( "something.else", undef )
460
461   join_addr
462          $addr = IO::Socket::IP->join_addr( $host, $port )
463
464       Utility method that performs the reverse of "split_addr", returning a
465       string formed by joining the specified host address and port number.
466       The host address will be wrapped in "[]" brackets if required (because
467       it is a raw IPv6 numeric address).
468
469       This can be especially useful when combined with the "sockhost_service"
470       or "peerhost_service" methods.
471
472        say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
473

"IO::Socket::INET" INCOMPATIBILITES

475       •   The behaviour enabled by "MultiHomed" is in fact implemented by
476           "IO::Socket::IP" as it is required to correctly support searching
477           for a useable address from the results of the getaddrinfo(3) call.
478           The constructor will ignore the value of this argument, except if
479           it is defined but false. An exception is thrown in this case,
480           because that would request it disable the getaddrinfo(3) search
481           behaviour in the first place.
482
483       •   "IO::Socket::IP" implements both the "Blocking" and "Timeout"
484           parameters, but it implements the interaction of both in a
485           different way.
486
487           In "::INET", supplying a timeout overrides the non-blocking
488           behaviour, meaning that the "connect()" operation will still block
489           despite that the caller asked for a non-blocking socket. This is
490           not explicitly specified in its documentation, nor does this author
491           believe that is a useful behaviour - it appears to come from a
492           quirk of implementation.
493
494           In "::IP" therefore, the "Blocking" parameter takes precedence - if
495           a non-blocking socket is requested, no operation will block. The
496           "Timeout" parameter here simply defines the maximum time that a
497           blocking "connect()" call will wait, if it blocks at all.
498
499           In order to specifically obtain the "blocking connect then non-
500           blocking send and receive" behaviour of specifying this combination
501           of options to "::INET" when using "::IP", perform first a blocking
502           connect, then afterwards turn the socket into nonblocking mode.
503
504            my $sock = IO::Socket::IP->new(
505               PeerHost => $peer,
506               Timeout => 20,
507            ) or die "Cannot connect - $@";
508
509            $sock->blocking( 0 );
510
511           This code will behave identically under both "IO::Socket::INET" and
512           "IO::Socket::IP".
513

TODO

515       •   Investigate whether "POSIX::dup2" upsets BSD's "kqueue" watchers,
516           and if so, consider what possible workarounds might be applied.
517

AUTHOR

519       Paul Evans <leonerd@leonerd.org.uk>
520
521
522
523perl v5.34.0                      2022-01-21                 IO::Socket::IP(3)
Impressum