blib/lib/Socket.pm

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