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