Debian Codegraph @

README

raw
1 NAME
2
3 IO::Socket::IP - Family-neutral IP socket supporting both IPv4 and IPv6
4
5 SYNOPSIS
6
7 use IO::Socket::IP;
8
9 my $sock = IO::Socket::IP->new(
10 PeerHost => "www.google.com",
11 PeerPort => "http",
12 Type => SOCK_STREAM,
13 ) or die "Cannot construct socket - $IO::Socket::errstr";
14
15 my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
16 ( $sock->sockdomain == PF_INET ) ? "IPv4" :
17 "unknown";
18
19 printf "Connected to google via %s\n", $familyname;
20
21 DESCRIPTION
22
23 This module provides a protocol-independent way to use IPv4 and IPv6
24 sockets, intended as a replacement for IO::Socket::INET. Most
25 constructor arguments and methods are provided in a backward-compatible
26 way. For a list of known differences, see the IO::Socket::INET
27 INCOMPATIBILITIES section below.
28
29 It uses the getaddrinfo(3) function to convert hostnames and service
30 names or port numbers into sets of possible addresses to connect to or
31 listen on. This allows it to work for IPv6 where the system supports
32 it, while still falling back to IPv4-only on systems which don't.
33
34 REPLACING IO::Socket DEFAULT BEHAVIOUR
35
36 By placing -register in the import list to IO::Socket::IP, it will
37 register itself with IO::Socket as the class that handles PF_INET. It
38 will also ask to handle PF_INET6 as well, provided that constant is
39 available.
40
41 Changing IO::Socket's default behaviour means that calling the
42 IO::Socket constructor with either PF_INET or PF_INET6 as the Domain
43 parameter will yield an IO::Socket::IP object.
44
45 use IO::Socket::IP -register;
46
47 my $sock = IO::Socket->new(
48 Domain => PF_INET6,
49 LocalHost => "::1",
50 Listen => 1,
51 ) or die "Cannot create socket - $IO::Socket::errstr\n";
52
53 print "Created a socket of type " . ref($sock) . "\n";
54
55 Note that -register is a global setting that applies to the entire
56 program; it cannot be applied only for certain callers, removed, or
57 limited by lexical scope.
58
59 CONSTRUCTORS
60
61 new
62
63 $sock = IO::Socket::IP->new( %args )
64
65 Creates a new IO::Socket::IP object, containing a newly created socket
66 handle according to the named arguments passed. The recognised
67 arguments are:
68
69 PeerHost => STRING
70
71 PeerService => STRING
72
73 Hostname and service name for the peer to connect() to. The service
74 name may be given as a port number, as a decimal string.
75
76 PeerAddr => STRING
77
78 PeerPort => STRING
79
80 For symmetry with the accessor methods and compatibility with
81 IO::Socket::INET, these are accepted as synonyms for PeerHost and
82 PeerService respectively.
83
84 PeerAddrInfo => ARRAY
85
86 Alternate form of specifying the peer to connect() to. This should be
87 an array of the form returned by Socket::getaddrinfo.
88
89 This parameter takes precedence over the Peer*, Family, Type and
90 Proto arguments.
91
92 LocalHost => STRING
93
94 LocalService => STRING
95
96 Hostname and service name for the local address to bind() to.
97
98 LocalAddr => STRING
99
100 LocalPort => STRING
101
102 For symmetry with the accessor methods and compatibility with
103 IO::Socket::INET, these are accepted as synonyms for LocalHost and
104 LocalService respectively.
105
106 LocalAddrInfo => ARRAY
107
108 Alternate form of specifying the local address to bind() to. This
109 should be an array of the form returned by Socket::getaddrinfo.
110
111 This parameter takes precedence over the Local*, Family, Type and
112 Proto arguments.
113
114 Family => INT
115
116 The address family to pass to getaddrinfo (e.g. AF_INET, AF_INET6).
117 Normally this will be left undefined, and getaddrinfo will search
118 using any address family supported by the system.
119
120 Type => INT
121
122 The socket type to pass to getaddrinfo (e.g. SOCK_STREAM,
123 SOCK_DGRAM). Normally defined by the caller; if left undefined
124 getaddrinfo may attempt to infer the type from the service name.
125
126 Proto => STRING or INT
127
128 The IP protocol to use for the socket (e.g. 'tcp', IPPROTO_TCP,
129 'udp',IPPROTO_UDP). Normally this will be left undefined, and either
130 getaddrinfo or the kernel will choose an appropriate value. May be
131 given either in string name or numeric form.
132
133 GetAddrInfoFlags => INT
134
135 More flags to pass to the getaddrinfo() function. If not supplied, a
136 default of AI_ADDRCONFIG will be used.
137
138 These flags will be combined with AI_PASSIVE if the Listen argument
139 is given. For more information see the documentation about
140 getaddrinfo() in the Socket module.
141
142 Listen => INT
143
144 If defined, puts the socket into listening mode where new connections
145 can be accepted using the accept method. The value given is used as
146 the listen(2) queue size.
147
148 ReuseAddr => BOOL
149
150 If true, set the SO_REUSEADDR sockopt
151
152 ReusePort => BOOL
153
154 If true, set the SO_REUSEPORT sockopt (not all OSes implement this
155 sockopt)
156
157 Broadcast => BOOL
158
159 If true, set the SO_BROADCAST sockopt
160
161 Sockopts => ARRAY
162
163 An optional array of other socket options to apply after the three
164 listed above. The value is an ARRAY containing 2- or 3-element
165 ARRAYrefs. Each inner array relates to a single option, giving the
166 level and option name, and an optional value. If the value element is
167 missing, it will be given the value of a platform-sized integer 1
168 constant (i.e. suitable to enable most of the common boolean
169 options).
170
171 For example, both options given below are equivalent to setting
172 ReuseAddr.
173
174 Sockopts => [
175 [ SOL_SOCKET, SO_REUSEADDR ],
176 [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],
177 ]
178
179 V6Only => BOOL
180
181 If defined, set the IPV6_V6ONLY sockopt when creating PF_INET6
182 sockets to the given value. If true, a listening-mode socket will
183 only listen on the AF_INET6 addresses; if false it will also accept
184 connections from AF_INET addresses.
185
186 If not defined, the socket option will not be changed, and default
187 value set by the operating system will apply. For repeatable
188 behaviour across platforms it is recommended this value always be
189 defined for listening-mode sockets.
190
191 Note that not all platforms support disabling this option. Some, at
192 least OpenBSD and MirBSD, will fail with EINVAL if you attempt to
193 disable it. To determine whether it is possible to disable, you may
194 use the class method
195
196 if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
197 ...
198 }
199 else {
200 ...
201 }
202
203 If your platform does not support disabling this option but you still
204 want to listen for both AF_INET and AF_INET6 connections you will
205 have to create two listening sockets, one bound to each protocol.
206
207 MultiHomed
208
209 This IO::Socket::INET-style argument is ignored, except if it is
210 defined but false. See the IO::Socket::INET INCOMPATIBILITIES section
211 below.
212
213 However, the behaviour it enables is always performed by
214 IO::Socket::IP.
215
216 Blocking => BOOL
217
218 If defined but false, the socket will be set to non-blocking mode.
219 Otherwise it will default to blocking mode. See the NON-BLOCKING
220 section below for more detail.
221
222 Timeout => NUM
223
224 If defined, gives a maximum time in seconds to block per connect()
225 call when in blocking mode. If missing, no timeout is applied other
226 than that provided by the underlying operating system. When in
227 non-blocking mode this parameter is ignored.
228
229 Note that if the hostname resolves to multiple address candidates,
230 the same timeout will apply to each connection attempt individually,
231 rather than to the operation as a whole. Further note that the
232 timeout does not apply to the initial hostname resolve operation, if
233 connecting by hostname.
234
235 This behaviour is copied inspired by IO::Socket::INET; for more fine
236 grained control over connection timeouts, consider performing a
237 nonblocking connect directly.
238
239 If neither Type nor Proto hints are provided, a default of SOCK_STREAM
240 and IPPROTO_TCP respectively will be set, to maintain compatibility
241 with IO::Socket::INET. Other named arguments that are not recognised
242 are ignored.
243
244 If neither Family nor any hosts or addresses are passed, nor any
245 *AddrInfo, then the constructor has no information on which to decide a
246 socket family to create. In this case, it performs a getaddrinfo call
247 with the AI_ADDRCONFIG flag, no host name, and a service name of "0",
248 and uses the family of the first returned result.
249
250 If the constructor fails, it will set $IO::Socket::errstr and $@ to an
251 appropriate error message; this may be from $! or it may be some other
252 string; not every failure necessarily has an associated errno value.
253
254 new (one arg)
255
256 $sock = IO::Socket::IP->new( $peeraddr )
257
258 As a special case, if the constructor is passed a single argument (as
259 opposed to an even-sized list of key/value pairs), it is taken to be
260 the value of the PeerAddr parameter. This is parsed in the same way,
261 according to the behaviour given in the PeerHost AND LocalHost PARSING
262 section below.
263
264 METHODS
265
266 As well as the following methods, this class inherits all the methods
267 in IO::Socket and IO::Handle.
268
269 sockhost_service
270
271 ( $host, $service ) = $sock->sockhost_service( $numeric );
272
273 Returns the hostname and service name of the local address (that is,
274 the socket address given by the sockname method).
275
276 If $numeric is true, these will be given in numeric form rather than
277 being resolved into names.
278
279 The following four convenience wrappers may be used to obtain one of
280 the two values returned here. If both host and service names are
281 required, this method is preferable to the following wrappers, because
282 it will call getnameinfo(3) only once.
283
284 sockhost
285
286 $addr = $sock->sockhost;
287
288 Return the numeric form of the local address as a textual
289 representation
290
291 sockport
292
293 $port = $sock->sockport;
294
295 Return the numeric form of the local port number
296
297 sockhostname
298
299 $host = $sock->sockhostname;
300
301 Return the resolved name of the local address
302
303 sockservice
304
305 $service = $sock->sockservice;
306
307 Return the resolved name of the local port number
308
309 sockaddr
310
311 $addr = $sock->sockaddr;
312
313 Return the local address as a binary octet string
314
315 peerhost_service
316
317 ( $host, $service ) = $sock->peerhost_service( $numeric );
318
319 Returns the hostname and service name of the peer address (that is, the
320 socket address given by the peername method), similar to the
321 sockhost_service method.
322
323 The following four convenience wrappers may be used to obtain one of
324 the two values returned here. If both host and service names are
325 required, this method is preferable to the following wrappers, because
326 it will call getnameinfo(3) only once.
327
328 peerhost
329
330 $addr = $sock->peerhost;
331
332 Return the numeric form of the peer address as a textual representation
333
334 peerport
335
336 $port = $sock->peerport;
337
338 Return the numeric form of the peer port number
339
340 peerhostname
341
342 $host = $sock->peerhostname;
343
344 Return the resolved name of the peer address
345
346 peerservice
347
348 $service = $sock->peerservice;
349
350 Return the resolved name of the peer port number
351
352 peeraddr
353
354 $addr = $peer->peeraddr;
355
356 Return the peer address as a binary octet string
357
358 as_inet
359
360 $inet = $sock->as_inet;
361
362 Returns a new IO::Socket::INET instance wrapping the same filehandle.
363 This may be useful in cases where it is required, for
364 backward-compatibility, to have a real object of IO::Socket::INET type
365 instead of IO::Socket::IP. The new object will wrap the same underlying
366 socket filehandle as the original, so care should be taken not to
367 continue to use both objects concurrently. Ideally the original $sock
368 should be discarded after this method is called.
369
370 This method checks that the socket domain is PF_INET and will throw an
371 exception if it isn't.
372
373 NON-BLOCKING
374
375 If the constructor is passed a defined but false value for the Blocking
376 argument then the socket is put into non-blocking mode. When in
377 non-blocking mode, the socket will not be set up by the time the
378 constructor returns, because the underlying connect(2) syscall would
379 otherwise have to block.
380
381 The non-blocking behaviour is an extension of the IO::Socket::INET API,
382 unique to IO::Socket::IP, because the former does not support
383 multi-homed non-blocking connect.
384
385 When using non-blocking mode, the caller must repeatedly check for
386 writeability on the filehandle (for instance using select or IO::Poll).
387 Each time the filehandle is ready to write, the connect method must be
388 called, with no arguments. Note that some operating systems, most
389 notably MSWin32 do not report a connect() failure using write-ready; so
390 you must also select() for exceptional status.
391
392 While connect returns false, the value of $! indicates whether it
393 should be tried again (by being set to the value EINPROGRESS, or
394 EWOULDBLOCK on MSWin32), or whether a permanent error has occurred
395 (e.g. ECONNREFUSED).
396
397 Once the socket has been connected to the peer, connect will return
398 true and the socket will now be ready to use.
399
400 Note that calls to the platform's underlying getaddrinfo(3) function
401 may block. If IO::Socket::IP has to perform this lookup, the
402 constructor will block even when in non-blocking mode.
403
404 To avoid this blocking behaviour, the caller should pass in the result
405 of such a lookup using the PeerAddrInfo or LocalAddrInfo arguments.
406 This can be achieved by using Net::LibAsyncNS, or the getaddrinfo(3)
407 function can be called in a child process.
408
409 use IO::Socket::IP;
410 use Errno qw( EINPROGRESS EWOULDBLOCK );
411
412 my @peeraddrinfo = ... # Caller must obtain the getaddrinfo result here
413
414 my $socket = IO::Socket::IP->new(
415 PeerAddrInfo => \@peeraddrinfo,
416 Blocking => 0,
417 ) or die "Cannot construct socket - $@";
418
419 while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
420 my $wvec = '';
421 vec( $wvec, fileno $socket, 1 ) = 1;
422 my $evec = '';
423 vec( $evec, fileno $socket, 1 ) = 1;
424
425 select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
426 }
427
428 die "Cannot connect - $!" if $!;
429
430 ...
431
432 The example above uses select(), but any similar mechanism should work
433 analogously. IO::Socket::IP takes care when creating new socket
434 filehandles to preserve the actual file descriptor number, so such
435 techniques as poll or epoll should be transparent to its reallocation
436 of a different socket underneath, perhaps in order to switch protocol
437 family between PF_INET and PF_INET6.
438
439 For another example using IO::Poll and Net::LibAsyncNS, see the
440 examples/nonblocking_libasyncns.pl file in the module distribution.
441
442 PeerHost AND LocalHost PARSING
443
444 To support the IO::Socket::INET API, the host and port information may
445 be passed in a single string rather than as two separate arguments.
446
447 If either LocalHost or PeerHost (or their ...Addr synonyms) have any of
448 the following special forms then special parsing is applied.
449
450 The value of the ...Host argument will be split to give both the
451 hostname and port (or service name):
452
453 hostname.example.org:http # Host name
454 192.0.2.1:80 # IPv4 address
455 [2001:db8::1]:80 # IPv6 address
456
457 In each case, the port or service name (e.g. 80) is passed as the
458 LocalService or PeerService argument.
459
460 Either of LocalService or PeerService (or their ...Port synonyms) can
461 be either a service name, a decimal number, or a string containing both
462 a service name and number, in a form such as
463
464 http(80)
465
466 In this case, the name (http) will be tried first, but if the resolver
467 does not understand it then the port number (80) will be used instead.
468
469 If the ...Host argument is in this special form and the corresponding
470 ...Service or ...Port argument is also defined, the one parsed from the
471 ...Host argument will take precedence and the other will be ignored.
472
473 split_addr
474
475 ( $host, $port ) = IO::Socket::IP->split_addr( $addr )
476
477 Utility method that provides the parsing functionality described above.
478 Returns a 2-element list, containing either the split hostname and port
479 description if it could be parsed, or the given address and undef if it
480 was not recognised.
481
482 IO::Socket::IP->split_addr( "hostname:http" );
483 # ( "hostname", "http" )
484
485 IO::Socket::IP->split_addr( "192.0.2.1:80" );
486 # ( "192.0.2.1", "80" )
487
488 IO::Socket::IP->split_addr( "[2001:db8::1]:80" );
489 # ( "2001:db8::1", "80" )
490
491 IO::Socket::IP->split_addr( "something.else" );
492 # ( "something.else", undef )
493
494 join_addr
495
496 $addr = IO::Socket::IP->join_addr( $host, $port )
497
498 Utility method that performs the reverse of split_addr, returning a
499 string formed by joining the specified host address and port number.
500 The host address will be wrapped in [] brackets if required (because it
501 is a raw IPv6 numeric address).
502
503 This can be especially useful when combined with the sockhost_service
504 or peerhost_service methods.
505
506 say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
507
508 IO::Socket::INET INCOMPATIBILITIES
509
510 * The behaviour enabled by MultiHomed is in fact implemented by
511 IO::Socket::IP as it is required to correctly support searching for a
512 useable address from the results of the getaddrinfo(3) call. The
513 constructor will ignore the value of this argument, except if it is
514 defined but false. An exception is thrown in this case, because that
515 would request it disable the getaddrinfo(3) search behaviour in the
516 first place.
517
518 * IO::Socket::IP implements both the Blocking and Timeout parameters,
519 but it implements the interaction of both in a different way.
520
521 In ::INET, supplying a timeout overrides the non-blocking behaviour,
522 meaning that the connect() operation will still block despite that
523 the caller asked for a non-blocking socket. This is not explicitly
524 specified in its documentation, nor does this author believe that is
525 a useful behaviour - it appears to come from a quirk of
526 implementation.
527
528 In ::IP therefore, the Blocking parameter takes precedence - if a
529 non-blocking socket is requested, no operation will block. The
530 Timeout parameter here simply defines the maximum time that a
531 blocking connect() call will wait, if it blocks at all.
532
533 In order to specifically obtain the "blocking connect then
534 non-blocking send and receive" behaviour of specifying this
535 combination of options to ::INET when using ::IP, perform first a
536 blocking connect, then afterwards turn the socket into nonblocking
537 mode.
538
539 my $sock = IO::Socket::IP->new(
540 PeerHost => $peer,
541 Timeout => 20,
542 ) or die "Cannot connect - $@";
543
544 $sock->blocking( 0 );
545
546 This code will behave identically under both IO::Socket::INET and
547 IO::Socket::IP.
548
549 TODO
550
551 * Investigate whether POSIX::dup2 upsets BSD's kqueue watchers, and
552 if so, consider what possible workarounds might be applied.
553
554 AUTHOR
555
556 Paul Evans <[email protected]>
557