← Index
NYTProf Performance Profile   « block view • line view • sub view »
For mentat.storage.mongo.pl
  Run on Tue Jun 24 09:58:41 2014
Reported on Tue Jun 24 09:59:14 2014

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