/usr/local/lib/perl5/5.44.0/x86_64-linux/Socket.pm

filter: Statementstmt 54.4% 37 / 68 Branchbran 3.5% 1 / 28 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 46.1% 6 / 13 Podpod 75.0% 3 / 4 totaltotal 36.7% 47 / 128 CC 16 SCAR 31.7
CC
16
Cov
36%
sockaddr_in
56.0
sockaddr_in6
30.0
sockaddr_un
20.0
CRAP 23.9
« /usr/local/lib/perl5/site_perl/5.44.0/Try/Tiny.pm ↑ Summary lib/Skilletor/Spec.pm »
1 package Socket;
2  
3 5 ▶use v5.6.1;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 our $VERSION = '2.041';
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 getaddrinfo() and getnameinfo() functions, and all the
63 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 getaddrinfo
398  
399 ($err, @result) = getaddrinfo $host, $service;
400  
401 ($err, @result) = getaddrinfo $host, $service, \%hints;
402  
403 Given both a hostname and service name, this function attempts to resolve the
404 host name into a list of network addresses, and the service name into a
405 protocol and port number, and then returns a list of address structures
406 suitable to connect() to it.
407  
408 Given just a host name, this function attempts to resolve it to a list of
409 network addresses, and then returns a list of address structures giving these
410 addresses.
411  
412 Given just a service name, this function attempts to resolve it to a protocol
413 and port number, and then returns a list of address structures that represent
414 it suitable to bind() to. This use should be combined with the C<AI_PASSIVE>
415 flag; see below.
416  
417 Given neither name, it generates an error.
418  
419 If present, $hints should be a reference to a hash, where the following keys
420 are recognised:
421  
422 =over 4
423  
424 =item flags => INT
425  
426 A bitfield containing C<AI_*> constants; see below.
427  
428 =item family => INT
429  
430 Restrict to only generating addresses in this address family
431  
432 =item socktype => INT
433  
434 Restrict to only generating addresses of this socket type
435  
436 =item protocol => INT
437  
438 Restrict to only generating addresses for this protocol
439  
440 =back
441  
442 The return value will be a list; the first value being an error indication,
443 followed by a list of address structures (if no error occurred).
444  
445 The error value will be a dualvar; comparable to the C<EAI_*> error constants,
446 or printable as a human-readable error message string. If no error occurred it
447 will be zero numerically and an empty string.
448  
449 Each value in the results list will be a hash reference containing the following
450 fields:
451  
452 =over 4
453  
454 =item family => INT
455  
456 The address family (e.g. C<AF_INET>)
457  
458 =item socktype => INT
459  
460 The socket type (e.g. C<SOCK_STREAM>)
461  
462 =item protocol => INT
463  
464 The protocol (e.g. C<IPPROTO_TCP>)
465  
466 =item addr => STRING
467  
468 The address in a packed string (such as would be returned by
469 pack_sockaddr_in())
470  
471 =item canonname => STRING
472  
473 The canonical name for the host if the C<AI_CANONNAME> flag was provided, or
474 C<undef> otherwise. This field will only be present on the first returned
475 address.
476  
477 =back
478  
479 The following flag constants are recognised in the $hints hash. Other flag
480 constants may exist as provided by the OS.
481  
482 =over 4
483  
484 =item AI_PASSIVE
485  
486 Indicates that this resolution is for a local bind() for a passive (i.e.
487 listening) socket, rather than an active (i.e. connecting) socket.
488  
489 =item AI_CANONNAME
490  
491 Indicates that the caller wishes the canonical hostname (C<canonname>) field
492 of the result to be filled in.
493  
494 =item AI_NUMERICHOST
495  
496 Indicates that the caller will pass a numeric address, rather than a hostname,
497 and that getaddrinfo() must not perform a resolve operation on this name. This
498 flag will prevent a possibly-slow network lookup operation, and instead return
499 an error if a hostname is passed.
500  
501 =back
502  
503 =head2 getnameinfo
504  
505 ($err, $hostname, $servicename) = getnameinfo $sockaddr,
506 $flags = 0, $xflags = 0;
507  
508 Given a packed socket address (such as from getsockname(), getpeername(), or
509 returned by getaddrinfo() in a C<addr> field), returns the hostname and
510 symbolic service name it represents. $flags may be a bitmask of C<NI_*>
511 constants, or defaults to 0 if unspecified.
512  
513 The return value will be a list; the first value being an error condition,
514 followed by the hostname and service name.
515  
516 The error value will be a dualvar; comparable to the C<EAI_*> error constants,
517 or printable as a human-readable error message string. The host and service
518 names will be plain strings.
519  
520 The following flag constants are recognised as $flags. Other flag constants may
521 exist as provided by the OS.
522  
523 =over 4
524  
525 =item NI_NUMERICHOST
526  
527 Requests that a human-readable string representation of the numeric address be
528 returned directly, rather than performing a name resolve operation that may
529 convert it into a hostname. This will also avoid potentially-blocking network
530 IO.
531  
532 =item NI_NUMERICSERV
533  
534 Requests that the port number be returned directly as a number representation
535 rather than performing a name resolve operation that may convert it into a
536 service name.
537  
538 =item NI_NAMEREQD
539  
540 If a name resolve operation fails to provide a name, then this flag will cause
541 getnameinfo() to indicate an error, rather than returning the numeric
542 representation as a human-readable string.
543  
544 =item NI_DGRAM
545  
546 Indicates that the socket address relates to a C<SOCK_DGRAM> socket, for the
547 services whose name differs between TCP and UDP protocols.
548  
549 =back
550  
551 The following constants may be supplied as $xflags.
552  
553 =over 4
554  
555 =item NIx_NOHOST
556  
557 Indicates that the caller is not interested in the hostname of the result, so
558 it does not have to be converted. C<undef> will be returned as the hostname.
559  
560 =item NIx_NOSERV
561  
562 Indicates that the caller is not interested in the service name of the result,
563 so it does not have to be converted. C<undef> will be returned as the service
564 name.
565  
566 =back
567  
568 =head1 getaddrinfo() / getnameinfo() ERROR CONSTANTS
569  
570 The following constants may be returned by getaddrinfo() or getnameinfo().
571 Others may be provided by the OS.
572  
573 =over 4
574  
575 =item EAI_AGAIN
576  
577 A temporary failure occurred during name resolution. The operation may be
578 successful if it is retried later.
579  
580 =item EAI_BADFLAGS
581  
582 The value of the C<flags> hint to getaddrinfo(), or the $flags parameter to
583 getnameinfo() contains unrecognised flags.
584  
585 =item EAI_FAMILY
586  
587 The C<family> hint to getaddrinfo(), or the family of the socket address
588 passed to getnameinfo() is not supported.
589  
590 =item EAI_NODATA
591  
592 The host name supplied to getaddrinfo() did not provide any usable address
593 data.
594  
595 =item EAI_NONAME
596  
597 The host name supplied to getaddrinfo() does not exist, or the address
598 supplied to getnameinfo() is not associated with a host name and the
599 C<NI_NAMEREQD> flag was supplied.
600  
601 =item EAI_SERVICE
602  
603 The service name supplied to getaddrinfo() is not available for the socket
604 type given in the $hints.
605  
606 =back
607  
608 =cut
609  
610 =head1 EXAMPLES
611  
612 =head2 Lookup for connect()
613  
614 The getaddrinfo() function converts a hostname and a service name into a list
615 of structures, each containing a potential way to connect() to the named
616 service on the named host.
617  
618 use IO::Socket;
619 use Socket qw(SOCK_STREAM getaddrinfo);
620  
621 my %hints = (socktype => SOCK_STREAM);
622 my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
623 die "Cannot getaddrinfo - $err" if $err;
624  
625 my $sock;
626  
627 foreach my $ai (@res) {
628 my $candidate = IO::Socket->new();
629  
630 $candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
631 or next;
632  
633 $candidate->connect($ai->{addr})
634 or next;
635  
636 $sock = $candidate;
637 last;
638 }
639  
640 die "Cannot connect to localhost:echo" unless $sock;
641  
642 $sock->print("Hello, world!\n");
643 print <$sock>;
644  
645 Because a list of potential candidates is returned, the C<while> loop tries
646 each in turn until it finds one that succeeds both the socket() and connect()
647 calls.
648  
649 This function performs the work of the legacy functions gethostbyname(),
650 getservbyname(), inet_aton() and pack_sockaddr_in().
651  
652 In practice this logic is better performed by L<IO::Socket::IP>.
653  
654 =head2 Making a human-readable string out of an address
655  
656 The getnameinfo() function converts a socket address, such as returned by
657 getsockname() or getpeername(), into a pair of human-readable strings
658 representing the address and service name.
659  
660 use IO::Socket::IP;
661 use Socket qw(getnameinfo);
662  
663 my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
664 die "Cannot listen - $@";
665  
666 my $socket = $server->accept or die "accept: $!";
667  
668 my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
669 die "Cannot getnameinfo - $err" if $err;
670  
671 print "The peer is connected from $hostname\n";
672  
673 Since in this example only the hostname was used, the redundant conversion of
674 the port number into a service name may be omitted by passing the
675 C<NIx_NOSERV> flag.
676  
677 use Socket qw(getnameinfo NIx_NOSERV);
678  
679 my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
680  
681 This function performs the work of the legacy functions unpack_sockaddr_in(),
682 inet_ntoa(), gethostbyaddr() and getservbyport().
683  
684 In practice this logic is better performed by L<IO::Socket::IP>.
685  
686 =head2 Resolving hostnames into IP addresses
687  
688 To turn a hostname into a human-readable plain IP address use getaddrinfo()
689 to turn the hostname into a list of socket structures, then getnameinfo() on
690 each one to make it a readable IP address again.
691  
692 use Socket qw(:addrinfo SOCK_RAW);
693  
694 my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
695 die "Cannot getaddrinfo - $err" if $err;
696  
697 while( my $ai = shift @res ) {
698 my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
699 die "Cannot getnameinfo - $err" if $err;
700  
701 print "$ipaddr\n";
702 }
703  
704 The C<socktype> hint to getaddrinfo() filters the results to only include one
705 socket type and protocol. Without this most OSes return three combinations,
706 for C<SOCK_STREAM>, C<SOCK_DGRAM> and C<SOCK_RAW>, resulting in triplicate
707 output of addresses. The C<NI_NUMERICHOST> flag to getnameinfo() causes it to
708 return a string-formatted plain IP address, rather than reverse resolving it
709 back into a hostname.
710  
711 This combination performs the work of the legacy functions gethostbyname()
712 and inet_ntoa().
713  
714 =head2 Accessing socket options
715  
716 The many C<SO_*> and other constants provide the socket option names for
717 getsockopt() and setsockopt().
718  
719 use IO::Socket::INET;
720 use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
721  
722 my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
723 or die "Cannot create socket: $@";
724  
725 $socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
726 die "setsockopt: $!";
727  
728 print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
729 " bytes\n";
730  
731 print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
732  
733 As a convenience, L<IO::Socket>'s setsockopt() method will convert a number
734 into a packed byte buffer, and getsockopt() will unpack a byte buffer of the
735 correct size back into a number.
736  
737 =cut
738  
739 =head1 AUTHOR
740  
741 This module was originally maintained in Perl core by the Perl 5 Porters.
742  
743 It was extracted to dual-life on CPAN at version 1.95 by
744 Paul Evans <leonerd@leonerd.org.uk>
745  
746 =cut
747  
748 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
749 5 ▶use warnings::register;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: not called CC=1 SCAR=0.0
750  
751 5 require Exporter;
752 5 require XSLoader;
753 5 our @ISA = qw(Exporter);
754  
755 # <@Nicholas> you can't change @EXPORT without breaking the implicit API
756 # Please put any new constants in @EXPORT_OK!
757  
758 # List re-ordered to match documentation above. Try to keep the ordering
759 # consistent so it's easier to see which ones are or aren't documented.
760 5 our @EXPORT = qw(
761 PF_802 PF_AAL PF_APPLETALK PF_CCITT PF_CHAOS PF_CTF PF_DATAKIT
762 PF_DECnet PF_DLI PF_ECMA PF_GOSIP PF_HYLINK PF_IMPLINK PF_INET PF_INET6
763 PF_ISO PF_KEY PF_LAST PF_LAT PF_LINK PF_MAX PF_NBS PF_NIT PF_NS PF_OSI
764 PF_OSINET PF_PUP PF_ROUTE PF_SNA PF_UNIX PF_UNSPEC PF_USER PF_WAN
765 PF_X25
766  
767 AF_802 AF_AAL AF_APPLETALK AF_CCITT AF_CHAOS AF_CTF AF_DATAKIT
768 AF_DECnet AF_DLI AF_ECMA AF_GOSIP AF_HYLINK AF_IMPLINK AF_INET AF_INET6
769 AF_ISO AF_KEY AF_LAST AF_LAT AF_LINK AF_MAX AF_NBS AF_NIT AF_NS AF_OSI
770 AF_OSINET AF_PUP AF_ROUTE AF_SNA AF_UNIX AF_UNSPEC AF_USER AF_WAN
771 AF_X25
772  
773 SOCK_DGRAM SOCK_RAW SOCK_RDM SOCK_SEQPACKET SOCK_STREAM
774  
775 SOL_SOCKET
776  
777 SO_ACCEPTCONN SO_ATTACH_FILTER SO_BACKLOG SO_BROADCAST SO_CHAMELEON
778 SO_DEBUG SO_DETACH_FILTER SO_DGRAM_ERRIND SO_DOMAIN SO_DONTLINGER
779 SO_DONTROUTE SO_ERROR SO_FAMILY SO_KEEPALIVE SO_LINGER SO_OOBINLINE
780 SO_PASSCRED SO_PASSIFNAME SO_PEERCRED SO_PROTOCOL SO_PROTOTYPE
781 SO_RCVBUF SO_RCVLOWAT SO_RCVTIMEO SO_REUSEADDR SO_REUSEPORT
782 SO_SECURITY_AUTHENTICATION SO_SECURITY_ENCRYPTION_NETWORK
783 SO_SECURITY_ENCRYPTION_TRANSPORT SO_SNDBUF SO_SNDLOWAT SO_SNDTIMEO
784 SO_STATE SO_TYPE SO_USELOOPBACK SO_XOPEN SO_XSE
785  
786 IP_HDRINCL IP_OPTIONS IP_RECVOPTS IP_RECVRETOPTS IP_RETOPTS IP_TOS
787 IP_TTL
788  
789 MSG_BCAST MSG_BTAG MSG_CTLFLAGS MSG_CTLIGNORE MSG_CTRUNC MSG_DONTROUTE
790 MSG_DONTWAIT MSG_EOF MSG_EOR MSG_ERRQUEUE MSG_ETAG MSG_FASTOPEN MSG_FIN
791 MSG_MAXIOVLEN MSG_MCAST MSG_NOSIGNAL MSG_OOB MSG_PEEK MSG_PROXY MSG_RST
792 MSG_SYN MSG_TRUNC MSG_URG MSG_WAITALL MSG_WIRE
793  
794 SHUT_RD SHUT_RDWR SHUT_WR
795  
796 INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
797  
798 SCM_CONNECT SCM_CREDENTIALS SCM_CREDS SCM_RIGHTS SCM_TIMESTAMP
799  
800 SOMAXCONN
801  
802 IOV_MAX
803 UIO_MAXIOV
804  
805 sockaddr_family
806 pack_sockaddr_in unpack_sockaddr_in sockaddr_in
807 pack_sockaddr_in6 unpack_sockaddr_in6 sockaddr_in6
808 pack_sockaddr_un unpack_sockaddr_un sockaddr_un
809  
810 inet_aton inet_ntoa
811 );
812  
813 # List re-ordered to match documentation above. Try to keep the ordering
814 # consistent so it's easier to see which ones are or aren't documented.
815 5 our @EXPORT_OK = qw(
816 CR LF CRLF $CR $LF $CRLF
817  
818 SOCK_NONBLOCK SOCK_CLOEXEC
819  
820 IP_ADD_MEMBERSHIP IP_ADD_SOURCE_MEMBERSHIP IP_BIND_ADDRESS_NO_PORT
821 IP_DROP_MEMBERSHIP IP_DROP_SOURCE_MEMBERSHIP IP_FREEBIND
822 IP_MULTICAST_ALL IP_MULTICAST_IF IP_MULTICAST_LOOP IP_MULTICAST_TTL
823 IP_MTU IP_MTU_DISCOVER IP_NODEFRAG IP_RECVERR IP_TRANSPARENT
824  
825 IPPROTO_IP IPPROTO_IPV6 IPPROTO_RAW IPPROTO_ICMP IPPROTO_IGMP
826 IPPROTO_TCP IPPROTO_UDP IPPROTO_GRE IPPROTO_ESP IPPROTO_AH
827 IPPROTO_ICMPV6 IPPROTO_SCTP
828  
829 IP_PMTUDISC_DO IP_PMTUDISC_DONT IP_PMTUDISC_PROBE IP_PMTUDISC_WANT
830  
831 IPTOS_LOWDELAY IPTOS_THROUGHPUT IPTOS_RELIABILITY IPTOS_MINCOST
832  
833 TCP_CC_INFO TCP_CONGESTION TCP_CONNECTIONTIMEOUT TCP_CORK TCP_DEFER_ACCEPT
834 TCP_FASTOPEN TCP_FASTOPEN_CONNECT TCP_FASTOPEN_KEY TCP_FASTOPEN_NO_COOKIE
835 TCP_INFO TCP_INIT_CWND TCP_KEEPALIVE TCP_KEEPCNT TCP_KEEPIDLE TCP_KEEPINTVL
836 TCP_LINGER2 TCP_MAXRT TCP_MAXSEG TCP_MD5SIG TCP_MD5SIG_EXT TCP_NODELAY
837 TCP_NOOPT TCP_NOPUSH TCP_NOTSENT_LOWAT TCP_QUICKACK TCP_SACK_ENABLE
838 TCP_STDURG TCP_SYNCNT TCP_TIMESTAMP TCP_TX_DELAY TCP_USER_TIMEOUT
839 TCP_WINDOW_CLAMP
840  
841 IN6ADDR_ANY IN6ADDR_LOOPBACK
842  
843 IPV6_ADDRFROM IPV6_ADD_MEMBERSHIP IPV6_DROP_MEMBERSHIP IPV6_JOIN_GROUP
844 IPV6_LEAVE_GROUP IPV6_MTU IPV6_MTU_DISCOVER IPV6_MULTICAST_HOPS
845 IPV6_MULTICAST_IF IPV6_MULTICAST_LOOP IPV6_RECVERR IPV6_ROUTER_ALERT
846 IPV6_TCLASS IPV6_UNICAST_HOPS IPV6_V6ONLY
847  
848 SO_INCOMING_CPU SO_INCOMING_NAPI_ID SO_LOCK_FILTER SO_RCVBUFFORCE
849 SO_SNDBUFFORCE
850  
851 pack_ip_mreq unpack_ip_mreq pack_ip_mreq_source unpack_ip_mreq_source
852  
853 pack_ipv6_mreq unpack_ipv6_mreq
854  
855 inet_pton inet_ntop
856  
857 getaddrinfo getnameinfo
858  
859 AI_ADDRCONFIG AI_ALL AI_CANONIDN AI_CANONNAME AI_IDN
860 AI_IDN_ALLOW_UNASSIGNED AI_IDN_USE_STD3_ASCII_RULES AI_NUMERICHOST
861 AI_NUMERICSERV AI_PASSIVE AI_V4MAPPED
862  
863 NI_DGRAM NI_IDN NI_IDN_ALLOW_UNASSIGNED NI_IDN_USE_STD3_ASCII_RULES
864 NI_NAMEREQD NI_NOFQDN NI_NUMERICHOST NI_NUMERICSERV
865  
866 NIx_NOHOST NIx_NOSERV
867  
868 EAI_ADDRFAMILY EAI_AGAIN EAI_BADFLAGS EAI_BADHINTS EAI_FAIL EAI_FAMILY
869 EAI_NODATA EAI_NONAME EAI_PROTOCOL EAI_SERVICE EAI_SOCKTYPE EAI_SYSTEM
870 );
871  
872 5 our %EXPORT_TAGS = (
873 crlf => [qw(CR LF CRLF $CR $LF $CRLF)],
874 addrinfo => [qw(getaddrinfo getnameinfo), grep m/^(?:AI|NI|NIx|EAI)_/, @EXPORT_OK],
875 all => [@EXPORT, @EXPORT_OK],
876 );
877  
878 BEGIN {
879 sub CR () {"\015"}
880 sub LF () {"\012"}
881 sub CRLF () {"\015\012"}
882  
883 # These are not gni() constants; they're extensions for the perl API
884 # The definitions in Socket.pm and Socket.xs must match
885 sub NIx_NOHOST() {1 << 0}
886 sub NIx_NOSERV() {1 << 1}
887 }
888  
889 5 *CR = \CR();
890 5 *LF = \LF();
891 5 *CRLF = \CRLF();
892  
893 # The four deprecated addrinfo constants
894 5 foreach my $name (qw( AI_IDN_ALLOW_UNASSIGNED AI_IDN_USE_STD3_ASCII_RULES NI_IDN_ALLOW_UNASSIGNED NI_IDN_USE_STD3_ASCII_RULES )) {
895 5 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
896 0 ▶ *$name = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
897 0 croak "The addrinfo constant $name is deprecated";
898 20 };
899 }
900  
901 0 ▶sub sockaddr_in {
Subroutine sockaddr_in: not called CC=7 SCAR=40.3
Pod documented
902 0 ▶ if (@_ == 6 && !wantarray) { # perl5.001m compat; use this && die
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 6 and not wantarray) { } 0 0 0
elsif (wantarray) { } 0 0 0
Condition0%0/3
@_ == 6 and not wantarray
!ll&&!rl&&r
000
MC/DC0%0/2
@_ == 6 and not wantarray
@_ == 6 not wantarray
Truth table0%0/3
A and not(B)
A= @_ == 6B= not wantarray
ABresult
0X0
100
111
903 0 my($af, $port, @quad) = @_;
904 0 ▶ warnings::warn "6-ARG sockaddr_in call is deprecated"
Branch: 1 branch
BranchTrueFalseTotal
if warnings::enabled() 0 0 0
905 if warnings::enabled();
906 0 pack_sockaddr_in($port, inet_aton(join('.', @quad)));
907 } elsif (wantarray) {
908 0 ▶ croak "usage: (port,iaddr) = sockaddr_in(sin_sv)" unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 0 0 0
909 0 unpack_sockaddr_in(@_);
910 } else {
911 0 ▶ croak "usage: sin_sv = sockaddr_in(port,iaddr))" unless @_ == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 2 0 0 0
912 0 pack_sockaddr_in(@_);
913 }
914 }
915  
916 0 ▶sub sockaddr_in6 {
Subroutine sockaddr_in6: not called CC=5 SCAR=34.0
Pod documented
917 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
918 0 ▶ croak "usage: (port,in6addr,scope_id,flowinfo) = sockaddr_in6(sin6_sv)" unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 0 0 0
919 0 unpack_sockaddr_in6(@_);
920 }
921 else {
922 0 ▶ croak "usage: sin6_sv = sockaddr_in6(port,in6addr,[scope_id,[flowinfo]])" unless @_ >= 2 and @_ <= 4;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ >= 2 and @_ <= 4 0 0 0
Condition0%0/3
@_ >= 2 and @_ <= 4
!ll&&!rl&&r
000
MC/DC0%0/2
@_ >= 2 and @_ <= 4
@_ >= 2 @_ <= 4
Truth table0%0/3
A and B
A= @_ >= 2B= @_ <= 4
ABresult
0X0
100
111
923 0 pack_sockaddr_in6(@_);
924 }
925 }
926  
927 0 ▶sub sockaddr_un {
Subroutine sockaddr_un: not called CC=4 SCAR=30.0
Pod documented
928 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
929 0 ▶ croak "usage: (filename) = sockaddr_un(sun_sv)" unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 0 0 0
930 0 unpack_sockaddr_un(@_);
931 } else {
932 0 ▶ croak "usage: sun_sv = sockaddr_un(filename)" unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 0 0 0
933 0 pack_sockaddr_un(@_);
934 }
935 }
936  
937 5 XSLoader::load(__PACKAGE__, $VERSION);
938  
939 5 my %errstr;
940  
941 5 ▶if( defined &getaddrinfo ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined &Socket::getaddrinfo) { } 5 0 5
942 # These are not part of the API, nothing uses them, and deleting them
943 # reduces the size of %Socket:: by about 12K
944 5 delete $Socket::{fake_getaddrinfo};
945 5 delete $Socket::{fake_getnameinfo};
946 } else {
947 0 require Scalar::Util;
948  
949 0 *getaddrinfo = \&fake_getaddrinfo;
950 0 *getnameinfo = \&fake_getnameinfo;
951  
952 # These numbers borrowed from GNU libc's implementation, but since
953 # they're only used by our emulation, it doesn't matter if the real
954 # platform's values differ
955 0 my %constants = (
956 AI_PASSIVE => 1,
957 AI_CANONNAME => 2,
958 AI_NUMERICHOST => 4,
959 AI_V4MAPPED => 8,
960 AI_ALL => 16,
961 AI_ADDRCONFIG => 32,
962 # RFC 2553 doesn't define this but Linux does - lets be nice and
963 # provide it since we can
964 AI_NUMERICSERV => 1024,
965  
966 EAI_BADFLAGS => -1,
967 EAI_NONAME => -2,
968 EAI_NODATA => -5,
969 EAI_FAMILY => -6,
970 EAI_SERVICE => -8,
971  
972 NI_NUMERICHOST => 1,
973 NI_NUMERICSERV => 2,
974 NI_NOFQDN => 4,
975 NI_NAMEREQD => 8,
976 NI_DGRAM => 16,
977  
978 # Constants we don't support. Export them, but croak if anyone tries to
979 # use them
980 AI_IDN => 64,
981 AI_CANONIDN => 128,
982 NI_IDN => 32,
983  
984 # Error constants we'll never return, so it doesn't matter what value
985 # these have, nor that we don't provide strings for them
986 EAI_SYSTEM => -11,
987 EAI_BADHINTS => -1000,
988 EAI_PROTOCOL => -1001
989 );
990  
991 0 foreach my $name ( keys %constants ) {
992 0 my $value = $constants{$name};
993  
994 5 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
995 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
996 }
997  
998 %errstr = (
999 # These strings from RFC 2553
1000 0 EAI_BADFLAGS() => "invalid value for ai_flags",
1001 EAI_NONAME() => "nodename nor servname provided, or not known",
1002 EAI_NODATA() => "no address associated with nodename",
1003 EAI_FAMILY() => "ai_family not supported",
1004 EAI_SERVICE() => "servname not supported for ai_socktype",
1005 );
1006 }
1007  
1008 # The following functions are used if the system does not have a
1009 # getaddrinfo(3) function in libc; and are used to emulate it for the AF_INET
1010 # family
1011  
1012 # Borrowed from Regexp::Common::net
1013 5 my $REGEXP_IPv4_DECIMAL = qr/25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}/;
1014 5 my $REGEXP_IPv4_DOTTEDQUAD = qr/$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL\.$REGEXP_IPv4_DECIMAL/;
1015  
1016 sub fake_makeerr
1017 0 ▶{
Subroutine fake_makeerr: not called CC=3 SCAR=24.8
Pod undocumented
1018 0 my ( $errno ) = @_;
1019 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
1020 0 return Scalar::Util::dualvar( $errno, $errstr );
1021 }
1022  
1023 sub fake_getaddrinfo
1024 {
1025 my ( $node, $service, $hints ) = @_;
1026  
1027 $node = "" unless defined $node;
1028  
1029 $service = "" unless defined $service;
1030  
1031 my ( $family, $socktype, $protocol, $flags ) = @$hints{qw( family socktype protocol flags )};
1032  
1033 $family ||= Socket::AF_INET(); # 0 == AF_UNSPEC, which we want too
1034 $family == Socket::AF_INET() or return fake_makeerr( EAI_FAMILY() );
1035  
1036 $socktype ||= 0;
1037  
1038 $protocol ||= 0;
1039  
1040 $flags ||= 0;
1041  
1042 my $flag_passive = $flags & AI_PASSIVE(); $flags &= ~AI_PASSIVE();
1043 my $flag_canonname = $flags & AI_CANONNAME(); $flags &= ~AI_CANONNAME();
1044 my $flag_numerichost = $flags & AI_NUMERICHOST(); $flags &= ~AI_NUMERICHOST();
1045 my $flag_numericserv = $flags & AI_NUMERICSERV(); $flags &= ~AI_NUMERICSERV();
1046  
1047 # These constants don't apply to AF_INET-only lookups, so we might as well
1048 # just ignore them. For AI_ADDRCONFIG we just presume the host has ability
1049 # to talk AF_INET. If not we'd have to return no addresses at all. :)
1050 $flags &= ~(AI_V4MAPPED()|AI_ALL()|AI_ADDRCONFIG());
1051  
1052 $flags & (AI_IDN()|AI_CANONIDN()) and
1053 croak "Socket::getaddrinfo() does not support IDN";
1054  
1055 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
1056  
1057 $node eq "" and $service eq "" and return fake_makeerr( EAI_NONAME() );
1058  
1059 my $canonname;
1060 my @addrs;
1061 if( $node ne "" ) {
1062 return fake_makeerr( EAI_NONAME() ) if( $flag_numerichost and $node !~ m/^$REGEXP_IPv4_DOTTEDQUAD$/ );
1063 ( $canonname, undef, undef, undef, @addrs ) = gethostbyname( $node );
1064 defined $canonname or return fake_makeerr( EAI_NONAME() );
1065  
1066 undef $canonname unless $flag_canonname;
1067 }
1068 else {
1069 $addrs[0] = $flag_passive ? Socket::inet_aton( "0.0.0.0" )
1070 : Socket::inet_aton( "127.0.0.1" );
1071 }
1072  
1073 my @ports; # Actually ARRAYrefs of [ socktype, protocol, port ]
1074 my $protname = "";
1075 if( $protocol ) {
1076 $protname = eval { getprotobynumber( $protocol ) };
1077 }
1078  
1079 if( $service ne "" and $service !~ m/^\d+$/ ) {
1080 return fake_makeerr( EAI_NONAME() ) if( $flag_numericserv );
1081 getservbyname( $service, $protname ) or return fake_makeerr( EAI_SERVICE() );
1082 }
1083  
1084 foreach my $this_socktype ( Socket::SOCK_STREAM(), Socket::SOCK_DGRAM(), Socket::SOCK_RAW() ) {
1085 next if $socktype and $this_socktype != $socktype;
1086  
1087 my $this_protname = "raw";
1088 $this_socktype == Socket::SOCK_STREAM() and $this_protname = "tcp";
1089 $this_socktype == Socket::SOCK_DGRAM() and $this_protname = "udp";
1090  
1091 next if $protname and $this_protname ne $protname;
1092  
1093 my $port;
1094 if( $service ne "" ) {
1095 if( $service =~ m/^\d+$/ ) {
1096 $port = "$service";
1097 }
1098 else {
1099 ( undef, undef, $port, $this_protname ) = getservbyname( $service, $this_protname );
1100 next unless defined $port;
1101 }
1102 }
1103 else {
1104 $port = 0;
1105 }
1106  
1107 push @ports, [ $this_socktype, eval { scalar getprotobyname( $this_protname ) } || 0, $port ];
1108 }
1109  
1110 my @ret;
1111 foreach my $addr ( @addrs ) {
1112 foreach my $portspec ( @ports ) {
1113 my ( $socktype, $protocol, $port ) = @$portspec;
1114 push @ret, {
1115 family => $family,
1116 socktype => $socktype,
1117 protocol => $protocol,
1118 addr => Socket::pack_sockaddr_in( $port, $addr ),
1119 canonname => undef,
1120 };
1121 }
1122 }
1123  
1124 # Only supply canonname for the first result
1125 if( defined $canonname ) {
1126 $ret[0]->{canonname} = $canonname;
1127 }
1128  
1129 return ( fake_makeerr( 0 ), @ret );
1130 }
1131  
1132 sub fake_getnameinfo
1133 {
1134 my ( $addr, $flags, $xflags ) = @_;
1135  
1136 my ( $port, $inetaddr );
1137 eval { ( $port, $inetaddr ) = Socket::unpack_sockaddr_in( $addr ) }
1138 or return fake_makeerr( EAI_FAMILY() );
1139  
1140 my $family = Socket::AF_INET();
1141  
1142 $flags ||= 0;
1143  
1144 my $flag_numerichost = $flags & NI_NUMERICHOST(); $flags &= ~NI_NUMERICHOST();
1145 my $flag_numericserv = $flags & NI_NUMERICSERV(); $flags &= ~NI_NUMERICSERV();
1146 my $flag_nofqdn = $flags & NI_NOFQDN(); $flags &= ~NI_NOFQDN();
1147 my $flag_namereqd = $flags & NI_NAMEREQD(); $flags &= ~NI_NAMEREQD();
1148 my $flag_dgram = $flags & NI_DGRAM() ; $flags &= ~NI_DGRAM();
1149  
1150 $flags & NI_IDN() and
1151 croak "Socket::getnameinfo() does not support IDN";
1152  
1153 $flags == 0 or return fake_makeerr( EAI_BADFLAGS() );
1154  
1155 $xflags ||= 0;
1156  
1157 my $node;
1158 if( $xflags & NIx_NOHOST ) {
1159 $node = undef;
1160 }
1161 elsif( $flag_numerichost ) {
1162 $node = Socket::inet_ntoa( $inetaddr );
1163 }
1164 else {
1165 $node = gethostbyaddr( $inetaddr, $family );
1166 if( !defined $node ) {
1167 return fake_makeerr( EAI_NONAME() ) if $flag_namereqd;
1168 $node = Socket::inet_ntoa( $inetaddr );
1169 }
1170 elsif( $flag_nofqdn ) {
1171 my ( $shortname ) = split m/\./, $node;
1172 my ( $fqdn ) = gethostbyname $shortname;
1173 $node = $shortname if defined $fqdn and $fqdn eq $node;
1174 }
1175 }
1176  
1177 my $service;
1178 if( $xflags & NIx_NOSERV ) {
1179 $service = undef;
1180 }
1181 elsif( $flag_numericserv ) {
1182 $service = "$port";
1183 }
1184 else {
1185 my $protname = $flag_dgram ? "udp" : "";
1186 $service = getservbyport( $port, $protname );
1187 if( !defined $service ) {
1188 $service = "$port";
1189 }
1190 }
1191  
1192 return ( fake_makeerr( 0 ), $node, $service );
1193 }
1194  
1195 5 1;
« /usr/local/lib/perl5/site_perl/5.44.0/Try/Tiny.pm ↑ Summary lib/Skilletor/Spec.pm »