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

CONSTRUCTORS

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

METHODS

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

NON-BLOCKING

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

"PeerHost" AND "LocalHost" PARSING

381       To support the "IO::Socket::INET" API, the host and port information
382       may be passed in a single string rather than as two separate arguments.
383
384       If either "LocalHost" or "PeerHost" (or their "...Addr" synonyms) have
385       any of the following special forms then special parsing is applied.
386
387       The value of the "...Host" argument will be split to give both the
388       hostname and port (or service name):
389
390        hostname.example.org:http    # Host name
391        192.0.2.1:80                 # IPv4 address
392        [2001:db8::1]:80             # IPv6 address
393
394       In each case, the port or service name (e.g. 80) is passed as the
395       "LocalService" or "PeerService" argument.
396
397       Either of "LocalService" or "PeerService" (or their "...Port" synonyms)
398       can be either a service name, a decimal number, or a string containing
399       both a service name and number, in a form such as
400
401        http(80)
402
403       In this case, the name ("http") will be tried first, but if the
404       resolver does not understand it then the port number (80) will be used
405       instead.
406
407       If the "...Host" argument is in this special form and the corresponding
408       "...Service" or "...Port" argument is also defined, the one parsed from
409       the "...Host" argument will take precedence and the other will be
410       ignored.
411
412   ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
413       Utility method that provides the parsing functionality described above.
414       Returns a 2-element list, containing either the split hostname and port
415       description if it could be parsed, or the given address and "undef" if
416       it was not recognised.
417
418        IO::Socket::IP->split_addr( "hostname:http" )
419                                     # ( "hostname",  "http" )
420
421        IO::Socket::IP->split_addr( "192.0.2.1:80" )
422                                     # ( "192.0.2.1", "80"   )
423
424        IO::Socket::IP->split_addr( "[2001:db8::1]:80" )
425                                     # ( "2001:db8::1", "80" )
426
427        IO::Socket::IP->split_addr( "something.else" )
428                                     # ( "something.else", undef )
429
430   $addr = IO::Socket::IP->join_addr( $host, $port )
431       Utility method that performs the reverse of "split_addr", returning a
432       string formed by joining the specified host address and port number.
433       The host address will be wrapped in "[]" brackets if required (because
434       it is a raw IPv6 numeric address).
435
436       This can be especially useful when combined with the "sockhost_service"
437       or "peerhost_service" methods.
438
439        say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
440

"IO::Socket::INET" INCOMPATIBILITES

442       ·   The behaviour enabled by "MultiHomed" is in fact implemented by
443           "IO::Socket::IP" as it is required to correctly support searching
444           for a useable address from the results of the getaddrinfo(3) call.
445           The constructor will ignore the value of this argument, except if
446           it is defined but false. An exception is thrown in this case,
447           because that would request it disable the getaddrinfo(3) search
448           behaviour in the first place.
449
450       ·   "IO::Socket::IP" implements both the "Blocking" and "Timeout"
451           parameters, but it implements the interaction of both in a
452           different way.
453
454           In "::INET", supplying a timeout overrides the non-blocking
455           behaviour, meaning that the "connect()" operation will still block
456           despite that the caller asked for a non-blocking socket. This is
457           not explicitly specified in its documentation, nor does this author
458           believe that is a useful behaviour - it appears to come from a
459           quirk of implementation.
460
461           In "::IP" therefore, the "Blocking" parameter takes precedence - if
462           a non-blocking socket is requested, no operation will block. The
463           "Timeout" parameter here simply defines the maximum time that a
464           blocking "connect()" call will wait, if it blocks at all.
465
466           In order to specifically obtain the "blocking connect then non-
467           blocking send and receive" behaviour of specifying this combination
468           of options to "::INET" when using "::IP", perform first a blocking
469           connect, then afterwards turn the socket into nonblocking mode.
470
471            my $sock = IO::Socket::IP->new(
472               PeerHost => $peer,
473               Timeout => 20,
474            ) or die "Cannot connect - $@";
475
476            $sock->blocking( 0 );
477
478           This code will behave identically under both "IO::Socket::INET" and
479           "IO::Socket::IP".
480

TODO

482       ·   Investigate whether "POSIX::dup2" upsets BSD's "kqueue" watchers,
483           and if so, consider what possible workarounds might be applied.
484

AUTHOR

486       Paul Evans <leonerd@leonerd.org.uk>
487
488
489
490perl v5.30.0                      2019-07-26                 IO::Socket::IP(3)
Impressum