This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Bump Socket version to 2.020_04
[perl5.git] / cpan / Socket / Socket.pm
1 package Socket;
2
3 use strict;
4 { use 5.006001; }
5
6 our $VERSION = '2.020_04'; # patched in perl5.git
7 $VERSION =~ tr/_//d;       # make $VERSION numeric
8
9 =head1 NAME
10
11 C<Socket> - networking constants and support functions
12
13 =head1 SYNOPSIS
14
15 C<Socket> a low-level module used by, among other things, the L<IO::Socket>
16 family of modules. The following examples demonstrate some low-level uses but
17 a practical program would likely use the higher-level API provided by
18 C<IO::Socket> or similar instead.
19
20  use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);
21
22  socket(my $socket, PF_INET, SOCK_STREAM, 0)
23      or die "socket: $!";
24
25  my $port = getservbyname "echo", "tcp";
26  connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
27      or die "connect: $!";
28
29  print $socket "Hello, world!\n";
30  print <$socket>;
31
32 See also the L</EXAMPLES> section.
33
34 =head1 DESCRIPTION
35
36 This module provides a variety of constants, structure manipulators and other
37 functions related to socket-based networking. The values and functions
38 provided are useful when used in conjunction with Perl core functions such as
39 socket(), setsockopt() and bind(). It also provides several other support
40 functions, mostly for dealing with conversions of network addresses between
41 human-readable and native binary forms, and for hostname resolver operations.
42
43 Some constants and functions are exported by default by this module; but for
44 backward-compatibility any recently-added symbols are not exported by default
45 and must be requested explicitly. When an import list is provided to the
46 C<use Socket> line, the default exports are not automatically imported. It is
47 therefore best practice to always to explicitly list all the symbols required.
48
49 Also, some common socket "newline" constants are provided: the constants
50 C<CR>, C<LF>, and C<CRLF>, as well as C<$CR>, C<$LF>, and C<$CRLF>, which map
51 to C<\015>, C<\012>, and C<\015\012>. If you do not want to use the literal
52 characters in your programs, then use the constants provided here. They are
53 not exported by default, but can be imported individually, and with the
54 C<:crlf> export tag:
55
56  use Socket qw(:DEFAULT :crlf);
57
58  $sock->print("GET / HTTP/1.0$CRLF");
59
60 The entire getaddrinfo() subsystem can be exported using the tag C<:addrinfo>;
61 this exports the getaddrinfo() and getnameinfo() functions, and all the
62 C<AI_*>, C<NI_*>, C<NIx_*> and C<EAI_*> constants.
63
64 =cut
65
66 =head1 CONSTANTS
67
68 In each of the following groups, there may be many more constants provided
69 than just the ones given as examples in the section heading. If the heading
70 ends C<...> then this means there are likely more; the exact constants
71 provided will depend on the OS and headers found at compile-time.
72
73 =cut
74
75 =head2 PF_INET, PF_INET6, PF_UNIX, ...
76
77 Protocol family constants to use as the first argument to socket() or the
78 value of the C<SO_DOMAIN> or C<SO_FAMILY> socket option.
79
80 =head2 AF_INET, AF_INET6, AF_UNIX, ...
81
82 Address family constants used by the socket address structures, to pass to
83 such functions as inet_pton() or getaddrinfo(), or are returned by such
84 functions as sockaddr_family().
85
86 =head2 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...
87
88 Socket type constants to use as the second argument to socket(), or the value
89 of the C<SO_TYPE> socket option.
90
91 =head2 SOCK_NONBLOCK. SOCK_CLOEXEC
92
93 Linux-specific shortcuts to specify the C<O_NONBLOCK> and C<FD_CLOEXEC> flags
94 during a C<socket(2)> call.
95
96  socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )
97
98 =head2 SOL_SOCKET
99
100 Socket option level constant for setsockopt() and getsockopt().
101
102 =head2 SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ...
103
104 Socket option name constants for setsockopt() and getsockopt() at the
105 C<SOL_SOCKET> level.
106
107 =head2 IP_OPTIONS, IP_TOS, IP_TTL, ...
108
109 Socket option name constants for IPv4 socket options at the C<IPPROTO_IP>
110 level.
111
112 =head2 IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ...
113
114 Socket option value constants for C<IP_TOS> socket option.
115
116 =head2 MSG_BCAST, MSG_OOB, MSG_TRUNC, ...
117
118 Message flag constants for send() and recv().
119
120 =head2 SHUT_RD, SHUT_RDWR, SHUT_WR
121
122 Direction constants for shutdown().
123
124 =head2 INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE
125
126 Constants giving the special C<AF_INET> addresses for wildcard, broadcast,
127 local loopback, and invalid addresses.
128
129 Normally equivalent to inet_aton('0.0.0.0'), inet_aton('255.255.255.255'),
130 inet_aton('localhost') and inet_aton('255.255.255.255') respectively.
131
132 =head2 IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ...
133
134 IP protocol constants to use as the third argument to socket(), the level
135 argument to getsockopt() or setsockopt(), or the value of the C<SO_PROTOCOL>
136 socket option.
137
138 =head2 TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ...
139
140 Socket option name constants for TCP socket options at the C<IPPROTO_TCP>
141 level.
142
143 =head2 IN6ADDR_ANY, IN6ADDR_LOOPBACK
144
145 Constants giving the special C<AF_INET6> addresses for wildcard and local
146 loopback.
147
148 Normally equivalent to inet_pton(AF_INET6, "::") and
149 inet_pton(AF_INET6, "::1") respectively.
150
151 =head2 IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...
152
153 Socket option name constants for IPv6 socket options at the C<IPPROTO_IPV6>
154 level.
155
156 =cut
157
158 # Still undocumented: SCM_*, SOMAXCONN, IOV_MAX, UIO_MAXIOV
159
160 =head1 STRUCTURE MANIPULATORS
161
162 The following functions convert between lists of Perl values and packed binary
163 strings representing structures.
164
165 =cut
166
167 =head2 $family = sockaddr_family $sockaddr
168
169 Takes a packed socket address (as returned by pack_sockaddr_in(),
170 pack_sockaddr_un() or the perl builtin functions getsockname() and
171 getpeername()). Returns the address family tag. This will be one of the
172 C<AF_*> constants, such as C<AF_INET> for a C<sockaddr_in> addresses or
173 C<AF_UNIX> for a C<sockaddr_un>. It can be used to figure out what unpack to
174 use for a sockaddr of unknown type.
175
176 =head2 $sockaddr = pack_sockaddr_in $port, $ip_address
177
178 Takes two arguments, a port number and an opaque string (as returned by
179 inet_aton(), or a v-string). Returns the C<sockaddr_in> structure with those
180 arguments packed in and C<AF_INET> filled in. For Internet domain sockets,
181 this structure is normally what you need for the arguments in bind(),
182 connect(), and send().
183
184 =head2 ($port, $ip_address) = unpack_sockaddr_in $sockaddr
185
186 Takes a C<sockaddr_in> structure (as returned by pack_sockaddr_in(),
187 getpeername() or recv()). Returns a list of two elements: the port and an
188 opaque string representing the IP address (you can use inet_ntoa() to convert
189 the address to the four-dotted numeric format). Will croak if the structure
190 does not represent an C<AF_INET> address.
191
192 In scalar context will return just the IP address.
193
194 =head2 $sockaddr = sockaddr_in $port, $ip_address
195
196 =head2 ($port, $ip_address) = sockaddr_in $sockaddr
197
198 A wrapper of pack_sockaddr_in() or unpack_sockaddr_in(). In list context,
199 unpacks its argument and returns a list consisting of the port and IP address.
200 In scalar context, packs its port and IP address arguments as a C<sockaddr_in>
201 and returns it.
202
203 Provided largely for legacy compatibility; it is better to use
204 pack_sockaddr_in() or unpack_sockaddr_in() explicitly.
205
206 =head2 $sockaddr = pack_sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
207
208 Takes two to four arguments, a port number, an opaque string (as returned by
209 inet_pton()), optionally a scope ID number, and optionally a flow label
210 number. Returns the C<sockaddr_in6> structure with those arguments packed in
211 and C<AF_INET6> filled in. IPv6 equivalent of pack_sockaddr_in().
212
213 =head2 ($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr
214
215 Takes a C<sockaddr_in6> structure. Returns a list of four elements: the port
216 number, an opaque string representing the IPv6 address, the scope ID, and the
217 flow label. (You can use inet_ntop() to convert the address to the usual
218 string format). Will croak if the structure does not represent an C<AF_INET6>
219 address.
220
221 In scalar context will return just the IP address.
222
223 =head2 $sockaddr = sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
224
225 =head2 ($port, $ip6_address, $scope_id, $flowinfo) = sockaddr_in6 $sockaddr
226
227 A wrapper of pack_sockaddr_in6() or unpack_sockaddr_in6(). In list context,
228 unpacks its argument according to unpack_sockaddr_in6(). In scalar context,
229 packs its arguments according to pack_sockaddr_in6().
230
231 Provided largely for legacy compatibility; it is better to use
232 pack_sockaddr_in6() or unpack_sockaddr_in6() explicitly.
233
234 =head2 $sockaddr = pack_sockaddr_un $path
235
236 Takes one argument, a pathname. Returns the C<sockaddr_un> structure with that
237 path packed in with C<AF_UNIX> filled in. For C<PF_UNIX> sockets, this
238 structure is normally what you need for the arguments in bind(), connect(),
239 and send().
240
241 =head2 ($path) = unpack_sockaddr_un $sockaddr
242
243 Takes a C<sockaddr_un> structure (as returned by pack_sockaddr_un(),
244 getpeername() or recv()). Returns a list of one element: the pathname. Will
245 croak if the structure does not represent an C<AF_UNIX> address.
246
247 =head2 $sockaddr = sockaddr_un $path
248
249 =head2 ($path) = sockaddr_un $sockaddr
250
251 A wrapper of pack_sockaddr_un() or unpack_sockaddr_un(). In a list context,
252 unpacks its argument and returns a list consisting of the pathname. In a
253 scalar context, packs its pathname as a C<sockaddr_un> and returns it.
254
255 Provided largely for legacy compatibility; it is better to use
256 pack_sockaddr_un() or unpack_sockaddr_un() explicitly.
257
258 These are only supported if your system has E<lt>F<sys/un.h>E<gt>.
259
260 =head2 $ip_mreq = pack_ip_mreq $multiaddr, $interface
261
262 Takes an IPv4 multicast address and optionally an interface address (or
263 C<INADDR_ANY>). Returns the C<ip_mreq> structure with those arguments packed
264 in. Suitable for use with the C<IP_ADD_MEMBERSHIP> and C<IP_DROP_MEMBERSHIP>
265 sockopts.
266
267 =head2 ($multiaddr, $interface) = unpack_ip_mreq $ip_mreq
268
269 Takes an C<ip_mreq> structure. Returns a list of two elements; the IPv4
270 multicast address and interface address.
271
272 =head2 $ip_mreq_source = pack_ip_mreq_source $multiaddr, $source, $interface
273
274 Takes an IPv4 multicast address, source address, and optionally an interface
275 address (or C<INADDR_ANY>). Returns the C<ip_mreq_source> structure with those
276 arguments packed in. Suitable for use with the C<IP_ADD_SOURCE_MEMBERSHIP>
277 and C<IP_DROP_SOURCE_MEMBERSHIP> sockopts.
278
279 =head2 ($multiaddr, $source, $interface) = unpack_ip_mreq_source $ip_mreq
280
281 Takes an C<ip_mreq_source> structure. Returns a list of three elements; the
282 IPv4 multicast address, source address and interface address.
283
284 =head2 $ipv6_mreq = pack_ipv6_mreq $multiaddr6, $ifindex
285
286 Takes an IPv6 multicast address and an interface number. Returns the
287 C<ipv6_mreq> structure with those arguments packed in. Suitable for use with
288 the C<IPV6_ADD_MEMBERSHIP> and C<IPV6_DROP_MEMBERSHIP> sockopts.
289
290 =head2 ($multiaddr6, $ifindex) = unpack_ipv6_mreq $ipv6_mreq
291
292 Takes an C<ipv6_mreq> structure. Returns a list of two elements; the IPv6
293 address and an interface number.
294
295 =cut
296
297 =head1 FUNCTIONS
298
299 =cut
300
301 =head2 $ip_address = inet_aton $string
302
303 Takes a string giving the name of a host, or a textual representation of an IP
304 address and translates that to an packed binary address structure suitable to
305 pass to pack_sockaddr_in(). If passed a hostname that cannot be resolved,
306 returns C<undef>. For multi-homed hosts (hosts with more than one address),
307 the first address found is returned.
308
309 For portability do not assume that the result of inet_aton() is 32 bits wide,
310 in other words, that it would contain only the IPv4 address in network order.
311
312 This IPv4-only function is provided largely for legacy reasons. Newly-written
313 code should use getaddrinfo() or inet_pton() instead for IPv6 support.
314
315 =head2 $string = inet_ntoa $ip_address
316
317 Takes a packed binary address structure such as returned by
318 unpack_sockaddr_in() (or a v-string representing the four octets of the IPv4
319 address in network order) and translates it into a string of the form
320 C<d.d.d.d> where the C<d>s are numbers less than 256 (the normal
321 human-readable four dotted number notation for Internet addresses).
322
323 This IPv4-only function is provided largely for legacy reasons. Newly-written
324 code should use getnameinfo() or inet_ntop() instead for IPv6 support.
325
326 =head2 $address = inet_pton $family, $string
327
328 Takes an address family (such as C<AF_INET> or C<AF_INET6>) and a string
329 containing a textual representation of an address in that family and
330 translates that to an packed binary address structure.
331
332 See also getaddrinfo() for a more powerful and flexible function to look up
333 socket addresses given hostnames or textual addresses.
334
335 =head2 $string = inet_ntop $family, $address
336
337 Takes an address family and a packed binary address structure and translates
338 it into a human-readable textual representation of the address; typically in
339 C<d.d.d.d> form for C<AF_INET> or C<hhhh:hhhh::hhhh> form for C<AF_INET6>.
340
341 See also getnameinfo() for a more powerful and flexible function to turn
342 socket addresses into human-readable textual representations.
343
344 =head2 ($err, @result) = getaddrinfo $host, $service, [$hints]
345
346 Given both a hostname and service name, this function attempts to resolve the
347 host name into a list of network addresses, and the service name into a
348 protocol and port number, and then returns a list of address structures
349 suitable to connect() to it.
350
351 Given just a host name, this function attempts to resolve it to a list of
352 network addresses, and then returns a list of address structures giving these
353 addresses.
354
355 Given just a service name, this function attempts to resolve it to a protocol
356 and port number, and then returns a list of address structures that represent
357 it suitable to bind() to. This use should be combined with the C<AI_PASSIVE>
358 flag; see below.
359
360 Given neither name, it generates an error.
361
362 If present, $hints should be a reference to a hash, where the following keys
363 are recognised:
364
365 =over 4
366
367 =item flags => INT
368
369 A bitfield containing C<AI_*> constants; see below.
370
371 =item family => INT
372
373 Restrict to only generating addresses in this address family
374
375 =item socktype => INT
376
377 Restrict to only generating addresses of this socket type
378
379 =item protocol => INT
380
381 Restrict to only generating addresses for this protocol
382
383 =back
384
385 The return value will be a list; the first value being an error indication,
386 followed by a list of address structures (if no error occurred).
387
388 The error value will be a dualvar; comparable to the C<EI_*> error constants,
389 or printable as a human-readable error message string. If no error occurred it
390 will be zero numerically and an empty string.
391
392 Each value in the results list will be a hash reference containing the following
393 fields:
394
395 =over 4
396
397 =item family => INT
398
399 The address family (e.g. C<AF_INET>)
400
401 =item socktype => INT
402
403 The socket type (e.g. C<SOCK_STREAM>)
404
405 =item protocol => INT
406
407 The protocol (e.g. C<IPPROTO_TCP>)
408
409 =item addr => STRING
410
411 The address in a packed string (such as would be returned by
412 pack_sockaddr_in())
413
414 =item canonname => STRING
415
416 The canonical name for the host if the C<AI_CANONNAME> flag was provided, or
417 C<undef> otherwise. This field will only be present on the first returned
418 address.
419
420 =back
421
422 The following flag constants are recognised in the $hints hash. Other flag
423 constants may exist as provided by the OS.
424
425 =over 4
426
427 =item AI_PASSIVE
428
429 Indicates that this resolution is for a local bind() for a passive (i.e.
430 listening) socket, rather than an active (i.e. connecting) socket.
431
432 =item AI_CANONNAME
433
434 Indicates that the caller wishes the canonical hostname (C<canonname>) field
435 of the result to be filled in.
436
437 =item AI_NUMERICHOST
438
439 Indicates that the caller will pass a numeric address, rather than a hostname,
440 and that getaddrinfo() must not perform a resolve operation on this name. This
441 flag will prevent a possibly-slow network lookup operation, and instead return
442 an error if a hostname is passed.
443
444 =back
445
446 =head2 ($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]]
447
448 Given a packed socket address (such as from getsockname(), getpeername(), or
449 returned by getaddrinfo() in a C<addr> field), returns the hostname and
450 symbolic service name it represents. $flags may be a bitmask of C<NI_*>
451 constants, or defaults to 0 if unspecified.
452
453 The return value will be a list; the first value being an error condition,
454 followed by the hostname and service name.
455
456 The error value will be a dualvar; comparable to the C<EI_*> error constants,
457 or printable as a human-readable error message string. The host and service
458 names will be plain strings.
459
460 The following flag constants are recognised as $flags. Other flag constants may
461 exist as provided by the OS.
462
463 =over 4
464
465 =item NI_NUMERICHOST
466
467 Requests that a human-readable string representation of the numeric address be
468 returned directly, rather than performing a name resolve operation that may
469 convert it into a hostname. This will also avoid potentially-blocking network
470 IO.
471
472 =item NI_NUMERICSERV
473
474 Requests that the port number be returned directly as a number representation
475 rather than performing a name resolve operation that may convert it into a
476 service name.
477
478 =item NI_NAMEREQD
479
480 If a name resolve operation fails to provide a name, then this flag will cause
481 getnameinfo() to indicate an error, rather than returning the numeric
482 representation as a human-readable string.
483
484 =item NI_DGRAM
485
486 Indicates that the socket address relates to a C<SOCK_DGRAM> socket, for the
487 services whose name differs between TCP and UDP protocols.
488
489 =back
490
491 The following constants may be supplied as $xflags.
492
493 =over 4
494
495 =item NIx_NOHOST
496
497 Indicates that the caller is not interested in the hostname of the result, so
498 it does not have to be converted. C<undef> will be returned as the hostname.
499
500 =item NIx_NOSERV
501
502 Indicates that the caller is not interested in the service name of the result,
503 so it does not have to be converted. C<undef> will be returned as the service
504 name.
505
506 =back
507
508 =head1 getaddrinfo() / getnameinfo() ERROR CONSTANTS
509
510 The following constants may be returned by getaddrinfo() or getnameinfo().
511 Others may be provided by the OS.
512
513 =over 4
514
515 =item EAI_AGAIN
516
517 A temporary failure occurred during name resolution. The operation may be
518 successful if it is retried later.
519
520 =item EAI_BADFLAGS
521
522 The value of the C<flags> hint to getaddrinfo(), or the $flags parameter to
523 getnameinfo() contains unrecognised flags.
524
525 =item EAI_FAMILY
526
527 The C<family> hint to getaddrinfo(), or the family of the socket address
528 passed to getnameinfo() is not supported.
529
530 =item EAI_NODATA
531
532 The host name supplied to getaddrinfo() did not provide any usable address
533 data.
534
535 =item EAI_NONAME
536
537 The host name supplied to getaddrinfo() does not exist, or the address
538 supplied to getnameinfo() is not associated with a host name and the
539 C<NI_NAMEREQD> flag was supplied.
540
541 =item EAI_SERVICE
542
543 The service name supplied to getaddrinfo() is not available for the socket
544 type given in the $hints.
545
546 =back
547
548 =cut
549
550 =head1 EXAMPLES
551
552 =head2 Lookup for connect()
553
554 The getaddrinfo() function converts a hostname and a service name into a list
555 of structures, each containing a potential way to connect() to the named
556 service on the named host.
557
558  use IO::Socket;
559  use Socket qw(SOCK_STREAM getaddrinfo);
560
561  my %hints = (socktype => SOCK_STREAM);
562  my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
563  die "Cannot getaddrinfo - $err" if $err;
564
565  my $sock;
566
567  foreach my $ai (@res) {
568      my $candidate = IO::Socket->new();
569
570      $candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
571          or next;
572
573      $candidate->connect($ai->{addr})
574          or next;
575
576      $sock = $candidate;
577      last;
578  }
579
580  die "Cannot connect to localhost:echo" unless $sock;
581
582  $sock->print("Hello, world!\n");
583  print <$sock>;
584
585 Because a list of potential candidates is returned, the C<while> loop tries
586 each in turn until it finds one that succeeds both the socket() and connect()
587 calls.
588
589 This function performs the work of the legacy functions gethostbyname(),
590 getservbyname(), inet_aton() and pack_sockaddr_in().
591
592 In practice this logic is better performed by L<IO::Socket::IP>.
593
594 =head2 Making a human-readable string out of an address
595
596 The getnameinfo() function converts a socket address, such as returned by
597 getsockname() or getpeername(), into a pair of human-readable strings
598 representing the address and service name.
599
600  use IO::Socket::IP;
601  use Socket qw(getnameinfo);
602
603  my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
604      die "Cannot listen - $@";
605
606  my $socket = $server->accept or die "accept: $!";
607
608  my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
609  die "Cannot getnameinfo - $err" if $err;
610
611  print "The peer is connected from $hostname\n";
612
613 Since in this example only the hostname was used, the redundant conversion of
614 the port number into a service name may be omitted by passing the
615 C<NIx_NOSERV> flag.
616
617  use Socket qw(getnameinfo NIx_NOSERV);
618
619  my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
620
621 This function performs the work of the legacy functions unpack_sockaddr_in(),
622 inet_ntoa(), gethostbyaddr() and getservbyport().
623
624 In practice this logic is better performed by L<IO::Socket::IP>.
625
626 =head2 Resolving hostnames into IP addresses
627
628 To turn a hostname into a human-readable plain IP address use getaddrinfo()
629 to turn the hostname into a list of socket structures, then getnameinfo() on
630 each one to make it a readable IP address again.
631
632  use Socket qw(:addrinfo SOCK_RAW);
633
634  my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
635  die "Cannot getaddrinfo - $err" if $err;
636
637  while( my $ai = shift @res ) {
638      my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
639      die "Cannot getnameinfo - $err" if $err;
640
641      print "$ipaddr\n";
642  }
643
644 The C<socktype> hint to getaddrinfo() filters the results to only include one
645 socket type and protocol. Without this most OSes return three combinations,
646 for C<SOCK_STREAM>, C<SOCK_DGRAM> and C<SOCK_RAW>, resulting in triplicate
647 output of addresses. The C<NI_NUMERICHOST> flag to getnameinfo() causes it to
648 return a string-formatted plain IP address, rather than reverse resolving it
649 back into a hostname.
650
651 This combination performs the work of the legacy functions gethostbyname()
652 and inet_ntoa().
653
654 =head2 Accessing socket options
655
656 The many C<SO_*> and other constants provide the socket option names for
657 getsockopt() and setsockopt().
658
659  use IO::Socket::INET;
660  use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
661
662  my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
663      or die "Cannot create socket: $@";
664
665  $socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
666      die "setsockopt: $!";
667
668  print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
669      " bytes\n";
670
671  print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
672
673 As a convenience, L<IO::Socket>'s setsockopt() method will convert a number
674 into a packed byte buffer, and getsockopt() will unpack a byte buffer of the
675 correct size back into a number.
676
677 =cut
678
679 =head1 AUTHOR
680
681 This module was originally maintained in Perl core by the Perl 5 Porters.
682
683 It was extracted to dual-life on CPAN at version 1.95 by
684 Paul Evans <leonerd@leonerd.org.uk>
685
686 =cut
687
688 use Carp;
689 use warnings::register;
690
691 require Exporter;
692 require XSLoader;
693 our @ISA = qw(Exporter);
694
695 # <@Nicholas> you can't change @EXPORT without breaking the implicit API
696 # Please put any new constants in @EXPORT_OK!
697
698 # List re-ordered to match documentation above. Try to keep the ordering
699 # consistent so it's easier to see which ones are or aren't documented.
700 our @EXPORT = qw(
701         PF_802 PF_AAL PF_APPLETALK PF_CCITT PF_CHAOS PF_CTF PF_DATAKIT
702         PF_DECnet PF_DLI PF_ECMA PF_GOSIP PF_HYLINK PF_IMPLINK PF_INET PF_INET6
703         PF_ISO PF_KEY PF_LAST PF_LAT PF_LINK PF_MAX PF_NBS PF_NIT PF_NS PF_OSI
704         PF_OSINET PF_PUP PF_ROUTE PF_SNA PF_UNIX PF_UNSPEC PF_USER PF_WAN
705         PF_X25
706
707         AF_802 AF_AAL AF_APPLETALK AF_CCITT AF_CHAOS AF_CTF AF_DATAKIT
708         AF_DECnet AF_DLI AF_ECMA AF_GOSIP AF_HYLINK AF_IMPLINK AF_INET AF_INET6
709         AF_ISO AF_KEY AF_LAST AF_LAT AF_LINK AF_MAX AF_NBS AF_NIT AF_NS AF_OSI
710         AF_OSINET AF_PUP AF_ROUTE AF_SNA AF_UNIX AF_UNSPEC AF_USER AF_WAN
711         AF_X25
712
713         SOCK_DGRAM SOCK_RAW SOCK_RDM SOCK_SEQPACKET SOCK_STREAM
714
715         SOL_SOCKET
716
717         SO_ACCEPTCONN SO_ATTACH_FILTER SO_BACKLOG SO_BROADCAST SO_CHAMELEON
718         SO_DEBUG SO_DETACH_FILTER SO_DGRAM_ERRIND SO_DOMAIN SO_DONTLINGER
719         SO_DONTROUTE SO_ERROR SO_FAMILY SO_KEEPALIVE SO_LINGER SO_OOBINLINE
720         SO_PASSCRED SO_PASSIFNAME SO_PEERCRED SO_PROTOCOL SO_PROTOTYPE
721         SO_RCVBUF SO_RCVLOWAT SO_RCVTIMEO SO_REUSEADDR SO_REUSEPORT
722         SO_SECURITY_AUTHENTICATION SO_SECURITY_ENCRYPTION_NETWORK
723         SO_SECURITY_ENCRYPTION_TRANSPORT SO_SNDBUF SO_SNDLOWAT SO_SNDTIMEO
724         SO_STATE SO_TYPE SO_USELOOPBACK SO_XOPEN SO_XSE
725
726         IP_OPTIONS IP_HDRINCL IP_TOS IP_TTL IP_RECVOPTS IP_RECVRETOPTS
727         IP_RETOPTS
728
729         MSG_BCAST MSG_BTAG MSG_CTLFLAGS MSG_CTLIGNORE MSG_CTRUNC MSG_DONTROUTE
730         MSG_DONTWAIT MSG_EOF MSG_EOR MSG_ERRQUEUE MSG_ETAG MSG_FIN
731         MSG_MAXIOVLEN MSG_MCAST MSG_NOSIGNAL MSG_OOB MSG_PEEK MSG_PROXY MSG_RST
732         MSG_SYN MSG_TRUNC MSG_URG MSG_WAITALL MSG_WIRE
733
734         SHUT_RD SHUT_RDWR SHUT_WR
735
736         INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
737
738         SCM_CONNECT SCM_CREDENTIALS SCM_CREDS SCM_RIGHTS SCM_TIMESTAMP
739
740         SOMAXCONN
741
742         IOV_MAX
743         UIO_MAXIOV
744
745         sockaddr_family
746         pack_sockaddr_in  unpack_sockaddr_in  sockaddr_in
747         pack_sockaddr_in6 unpack_sockaddr_in6 sockaddr_in6
748         pack_sockaddr_un  unpack_sockaddr_un  sockaddr_un 
749
750         inet_aton inet_ntoa
751 );
752
753 # List re-ordered to match documentation above. Try to keep the ordering
754 # consistent so it's easier to see which ones are or aren't documented.
755 our @EXPORT_OK = qw(
756         CR LF CRLF $CR $LF $CRLF
757
758         SOCK_NONBLOCK SOCK_CLOEXEC
759
760         IP_ADD_MEMBERSHIP IP_ADD_SOURCE_MEMBERSHIP IP_DROP_MEMBERSHIP
761         IP_DROP_SOURCE_MEMBERSHIP IP_MULTICAST_IF IP_MULTICAST_LOOP
762         IP_MULTICAST_TTL
763
764         IPPROTO_IP IPPROTO_IPV6 IPPROTO_RAW IPPROTO_ICMP IPPROTO_IGMP
765         IPPROTO_TCP IPPROTO_UDP IPPROTO_GRE IPPROTO_ESP IPPROTO_AH
766         IPPROTO_SCTP
767
768         IPTOS_LOWDELAY IPTOS_THROUGHPUT IPTOS_RELIABILITY IPTOS_MINCOST
769
770         TCP_CONGESTION TCP_CONNECTIONTIMEOUT TCP_CORK TCP_DEFER_ACCEPT TCP_INFO
771         TCP_INIT_CWND TCP_KEEPALIVE TCP_KEEPCNT TCP_KEEPIDLE TCP_KEEPINTVL
772         TCP_LINGER2 TCP_MAXRT TCP_MAXSEG TCP_MD5SIG TCP_NODELAY TCP_NOOPT
773         TCP_NOPUSH TCP_QUICKACK TCP_SACK_ENABLE TCP_STDURG TCP_SYNCNT
774         TCP_WINDOW_CLAMP
775
776         IN6ADDR_ANY IN6ADDR_LOOPBACK
777
778         IPV6_ADD_MEMBERSHIP IPV6_DROP_MEMBERSHIP IPV6_JOIN_GROUP
779         IPV6_LEAVE_GROUP IPV6_MTU IPV6_MTU_DISCOVER IPV6_MULTICAST_HOPS
780         IPV6_MULTICAST_IF IPV6_MULTICAST_LOOP IPV6_UNICAST_HOPS IPV6_V6ONLY
781
782         pack_ip_mreq unpack_ip_mreq pack_ip_mreq_source unpack_ip_mreq_source
783
784         pack_ipv6_mreq unpack_ipv6_mreq
785
786         inet_pton inet_ntop
787
788         getaddrinfo getnameinfo
789
790         AI_ADDRCONFIG AI_ALL AI_CANONIDN AI_CANONNAME AI_IDN
791         AI_IDN_ALLOW_UNASSIGNED AI_IDN_USE_STD3_ASCII_RULES AI_NUMERICHOST
792         AI_NUMERICSERV AI_PASSIVE AI_V4MAPPED
793
794         NI_DGRAM NI_IDN NI_IDN_ALLOW_UNASSIGNED NI_IDN_USE_STD3_ASCII_RULES
795         NI_NAMEREQD NI_NOFQDN NI_NUMERICHOST NI_NUMERICSERV
796
797         NIx_NOHOST NIx_NOSERV
798
799         EAI_ADDRFAMILY EAI_AGAIN EAI_BADFLAGS EAI_BADHINTS EAI_FAIL EAI_FAMILY
800         EAI_NODATA EAI_NONAME EAI_PROTOCOL EAI_SERVICE EAI_SOCKTYPE EAI_SYSTEM
801 );
802
803 our %EXPORT_TAGS = (
804     crlf     => [qw(CR LF CRLF $CR $LF $CRLF)],
805     addrinfo => [qw(getaddrinfo getnameinfo), grep m/^(?:AI|NI|NIx|EAI)_/, @EXPORT_OK],
806     all      => [@EXPORT, @EXPORT_OK],
807 );
808
809 BEGIN {
810     sub CR   () {"\015"}
811     sub LF   () {"\012"}
812     sub CRLF () {"\015\012"}
813
814     # These are not gni() constants; they're extensions for the perl API
815     # The definitions in Socket.pm and Socket.xs must match
816     sub NIx_NOHOST() {1 << 0}
817     sub NIx_NOSERV() {1 << 1}
818 }
819
820 *CR   = \CR();
821 *LF   = \LF();
822 *CRLF = \CRLF();
823
824 sub sockaddr_in {
825     if (@_ == 6 && !wantarray) { # perl5.001m compat; use this && die
826         my($af, $port, @quad) = @_;
827         warnings::warn "6-ARG sockaddr_in call is deprecated" 
828             if warnings::enabled();
829         pack_sockaddr_in($port, inet_aton(join('.', @quad)));
830     } elsif (wantarray) {
831         croak "usage:   (port,iaddr) = sockaddr_in(sin_sv)" unless @_ == 1;
832         unpack_sockaddr_in(@_);
833     } else {
834         croak "usage:   sin_sv = sockaddr_in(port,iaddr))" unless @_ == 2;
835         pack_sockaddr_in(@_);
836     }
837 }
838
839 sub sockaddr_in6 {
840     if (wantarray) {
841         croak "usage:   (port,in6addr,scope_id,flowinfo) = sockaddr_in6(sin6_sv)" unless @_ == 1;
842         unpack_sockaddr_in6(@_);
843     }
844     else {
845         croak "usage:   sin6_sv = sockaddr_in6(port,in6addr,[scope_id,[flowinfo]])" unless @_ >= 2 and @_ <= 4;
846         pack_sockaddr_in6(@_);
847     }
848 }
849
850 sub sockaddr_un {
851     if (wantarray) {
852         croak "usage:   (filename) = sockaddr_un(sun_sv)" unless @_ == 1;
853         unpack_sockaddr_un(@_);
854     } else {
855         croak "usage:   sun_sv = sockaddr_un(filename)" unless @_ == 1;
856         pack_sockaddr_un(@_);
857     }
858 }
859
860 XSLoader::load(__PACKAGE__, $VERSION);
861
862 my %errstr;
863
864 if( defined &getaddrinfo ) {
865     # These are not part of the API, nothing uses them, and deleting them
866     # reduces the size of %Socket:: by about 12K
867     delete $Socket::{fake_getaddrinfo};
868     delete $Socket::{fake_getnameinfo};
869 } else {
870     require Scalar::Util;
871
872     *getaddrinfo = \&fake_getaddrinfo;
873     *getnameinfo = \&fake_getnameinfo;
874
875     # These numbers borrowed from GNU libc's implementation, but since
876     # they're only used by our emulation, it doesn't matter if the real
877     # platform's values differ
878     my %constants = (
879         AI_PASSIVE     => 1,
880         AI_CANONNAME   => 2,
881         AI_NUMERICHOST => 4,
882         AI_V4MAPPED    => 8,
883         AI_ALL         => 16,
884         AI_ADDRCONFIG  => 32,
885         # RFC 2553 doesn't define this but Linux does - lets be nice and
886         # provide it since we can
887         AI_NUMERICSERV => 1024,
888
889         EAI_BADFLAGS   => -1,
890         EAI_NONAME     => -2,
891         EAI_NODATA     => -5,
892         EAI_FAMILY     => -6,
893         EAI_SERVICE    => -8,
894
895         NI_NUMERICHOST => 1,
896         NI_NUMERICSERV => 2,
897         NI_NOFQDN      => 4,
898         NI_NAMEREQD    => 8,
899         NI_DGRAM       => 16,
900
901         # Constants we don't support. Export them, but croak if anyone tries to
902         # use them
903         AI_IDN                      => 64,
904         AI_CANONIDN                 => 128,
905         AI_IDN_ALLOW_UNASSIGNED     => 256,
906         AI_IDN_USE_STD3_ASCII_RULES => 512,
907         NI_IDN                      => 32,
908         NI_IDN_ALLOW_UNASSIGNED     => 64,
909         NI_IDN_USE_STD3_ASCII_RULES => 128,
910
911         # Error constants we'll never return, so it doesn't matter what value
912         # these have, nor that we don't provide strings for them
913         EAI_SYSTEM   => -11,
914         EAI_BADHINTS => -1000,
915         EAI_PROTOCOL => -1001
916     );
917
918     foreach my $name ( keys %constants ) {
919         my $value = $constants{$name};
920
921         no strict 'refs';
922         defined &$name or *$name = sub () { $value };
923     }
924
925     %errstr = (
926         # These strings from RFC 2553
927         EAI_BADFLAGS()   => "invalid value for ai_flags",
928         EAI_NONAME()     => "nodename nor servname provided, or not known",
929         EAI_NODATA()     => "no address associated with nodename",
930         EAI_FAMILY()     => "ai_family not supported",
931         EAI_SERVICE()    => "servname not supported for ai_socktype",
932     );
933 }
934
935 # The following functions are used if the system does not have a
936 # getaddrinfo(3) function in libc; and are used to emulate it for the AF_INET
937 # family
938
939 # Borrowed from Regexp::Common::net
940 my $REGEXP_IPv4_DECIMAL = qr/25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}/;
941 my $REGEXP_IPv4_DOTTEDQUAD = qr/$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL/;
942
943 sub fake_makeerr
944 {
945     my ( $errno ) = @_;
946     my $errstr = $errno == 0 ? "" : ( $errstr{$errno} || $errno );
947     return Scalar::Util::dualvar( $errno, $errstr );
948 }
949
950 sub fake_getaddrinfo
951 {
952     my ( $node, $service, $hints ) = @_;
953
954     $node = "" unless defined $node;
955
956     $service = "" unless defined $service;
957
958     my ( $family, $socktype, $protocol, $flags ) = @$hints{qw( family socktype protocol flags )};
959
960     $family ||= Socket::AF_INET(); # 0 == AF_UNSPEC, which we want too
961     $family == Socket::AF_INET() or return fake_makeerr( EAI_FAMILY() );
962
963     $socktype ||= 0;
964
965     $protocol ||= 0;
966
967     $flags ||= 0;
968
969     my $flag_passive     = $flags & AI_PASSIVE();     $flags &= ~AI_PASSIVE();
970     my $flag_canonname   = $flags & AI_CANONNAME();   $flags &= ~AI_CANONNAME();
971     my $flag_numerichost = $flags & AI_NUMERICHOST(); $flags &= ~AI_NUMERICHOST();
972     my $flag_numericserv = $flags & AI_NUMERICSERV(); $flags &= ~AI_NUMERICSERV();
973
974     # These constants don't apply to AF_INET-only lookups, so we might as well
975     # just ignore them. For AI_ADDRCONFIG we just presume the host has ability
976     # to talk AF_INET. If not we'd have to return no addresses at all. :)
977     $flags &= ~(AI_V4MAPPED()|AI_ALL()|AI_ADDRCONFIG());
978
979     $flags & (AI_IDN()|AI_CANONIDN()|AI_IDN_ALLOW_UNASSIGNED()|AI_IDN_USE_STD3_ASCII_RULES()) and
980         croak "Socket::getaddrinfo() does not support IDN";
981
982     $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
983
984     $node eq "" and $service eq "" and return fake_makeerr( EAI_NONAME() );
985
986     my $canonname;
987     my @addrs;
988     if( $node ne "" ) {
989         return fake_makeerr( EAI_NONAME() ) if( $flag_numerichost and $node !~ m/^$REGEXP_IPv4_DOTTEDQUAD$/ );
990         ( $canonname, undef, undef, undef, @addrs ) = gethostbyname( $node );
991         defined $canonname or return fake_makeerr( EAI_NONAME() );
992
993         undef $canonname unless $flag_canonname;
994     }
995     else {
996         $addrs[0] = $flag_passive ? Socket::inet_aton( "0.0.0.0" )
997                                   : Socket::inet_aton( "127.0.0.1" );
998     }
999
1000     my @ports; # Actually ARRAYrefs of [ socktype, protocol, port ]
1001     my $protname = "";
1002     if( $protocol ) {
1003         $protname = eval { getprotobynumber( $protocol ) };
1004     }
1005
1006     if( $service ne "" and $service !~ m/^\d+$/ ) {
1007         return fake_makeerr( EAI_NONAME() ) if( $flag_numericserv );
1008         getservbyname( $service, $protname ) or return fake_makeerr( EAI_SERVICE() );
1009     }
1010
1011     foreach my $this_socktype ( Socket::SOCK_STREAM(), Socket::SOCK_DGRAM(), Socket::SOCK_RAW() ) {
1012         next if $socktype and $this_socktype != $socktype;
1013
1014         my $this_protname = "raw";
1015         $this_socktype == Socket::SOCK_STREAM() and $this_protname = "tcp";
1016         $this_socktype == Socket::SOCK_DGRAM()  and $this_protname = "udp";
1017
1018         next if $protname and $this_protname ne $protname;
1019
1020         my $port;
1021         if( $service ne "" ) {
1022             if( $service =~ m/^\d+$/ ) {
1023                 $port = "$service";
1024             }
1025             else {
1026                 ( undef, undef, $port, $this_protname ) = getservbyname( $service, $this_protname );
1027                 next unless defined $port;
1028             }
1029         }
1030         else {
1031             $port = 0;
1032         }
1033
1034         push @ports, [ $this_socktype, eval { scalar getprotobyname( $this_protname ) } || 0, $port ];
1035     }
1036
1037     my @ret;
1038     foreach my $addr ( @addrs ) {
1039         foreach my $portspec ( @ports ) {
1040             my ( $socktype, $protocol, $port ) = @$portspec;
1041             push @ret, {
1042                 family    => $family,
1043                 socktype  => $socktype,
1044                 protocol  => $protocol,
1045                 addr      => Socket::pack_sockaddr_in( $port, $addr ),
1046                 canonname => undef,
1047             };
1048         }
1049     }
1050
1051     # Only supply canonname for the first result
1052     if( defined $canonname ) {
1053         $ret[0]->{canonname} = $canonname;
1054     }
1055
1056     return ( fake_makeerr( 0 ), @ret );
1057 }
1058
1059 sub fake_getnameinfo
1060 {
1061     my ( $addr, $flags, $xflags ) = @_;
1062
1063     my ( $port, $inetaddr );
1064     eval { ( $port, $inetaddr ) = Socket::unpack_sockaddr_in( $addr ) }
1065         or return fake_makeerr( EAI_FAMILY() );
1066
1067     my $family = Socket::AF_INET();
1068
1069     $flags ||= 0;
1070
1071     my $flag_numerichost = $flags & NI_NUMERICHOST(); $flags &= ~NI_NUMERICHOST();
1072     my $flag_numericserv = $flags & NI_NUMERICSERV(); $flags &= ~NI_NUMERICSERV();
1073     my $flag_nofqdn      = $flags & NI_NOFQDN();      $flags &= ~NI_NOFQDN();
1074     my $flag_namereqd    = $flags & NI_NAMEREQD();    $flags &= ~NI_NAMEREQD();
1075     my $flag_dgram       = $flags & NI_DGRAM()   ;    $flags &= ~NI_DGRAM();
1076
1077     $flags & (NI_IDN()|NI_IDN_ALLOW_UNASSIGNED()|NI_IDN_USE_STD3_ASCII_RULES()) and
1078         croak "Socket::getnameinfo() does not support IDN";
1079
1080     $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
1081
1082     $xflags ||= 0;
1083
1084     my $node;
1085     if( $xflags & NIx_NOHOST ) {
1086         $node = undef;
1087     }
1088     elsif( $flag_numerichost ) {
1089         $node = Socket::inet_ntoa( $inetaddr );
1090     }
1091     else {
1092         $node = gethostbyaddr( $inetaddr, $family );
1093         if( !defined $node ) {
1094             return fake_makeerr( EAI_NONAME() ) if $flag_namereqd;
1095             $node = Socket::inet_ntoa( $inetaddr );
1096         }
1097         elsif( $flag_nofqdn ) {
1098             my ( $shortname ) = split m/\./, $node;
1099             my ( $fqdn ) = gethostbyname $shortname;
1100             $node = $shortname if defined $fqdn and $fqdn eq $node;
1101         }
1102     }
1103
1104     my $service;
1105     if( $xflags & NIx_NOSERV ) {
1106         $service = undef;
1107     }
1108     elsif( $flag_numericserv ) {
1109         $service = "$port";
1110     }
1111     else {
1112         my $protname = $flag_dgram ? "udp" : "";
1113         $service = getservbyport( $port, $protname );
1114         if( !defined $service ) {
1115             $service = "$port";
1116         }
1117     }
1118
1119     return ( fake_makeerr( 0 ), $node, $service );
1120 }
1121
1122 1;