1Socket::GetAddrInfo(3)User Contributed Perl DocumentationSocket::GetAddrInfo(3)
2
3
4

NAME

6       "Socket::GetAddrInfo" - address-family independent name resolving
7       functions
8

SYNOPSIS

10        use Socket qw( SOCK_STREAM );
11        use Socket::GetAddrInfo qw( getaddrinfo getnameinfo );
12        use IO::Socket;
13
14        my %hints = ( socktype => SOCK_STREAM );
15        my ( $err, @res ) = getaddrinfo( "www.google.com", "www", \%hints );
16
17        die "Cannot resolve name - $err" if $err;
18
19        my $sock;
20
21        foreach my $ai ( @res ) {
22           my $candidate = IO::Socket->new();
23
24           $candidate->socket( $ai->{family}, $ai->{socktype}, $ai->{protocol} )
25              or next;
26
27           $candidate->connect( $ai->{addr} )
28              or next;
29
30           $sock = $candidate;
31           last;
32        }
33
34        if( $sock ) {
35           my ( $err, $host, $service ) = getnameinfo( $sock->peername );
36           print "Connected to $host:$service\n" if !$err;
37        }
38

DESCRIPTION

40       The RFC 2553 functions "getaddrinfo" and "getnameinfo" provide an
41       abstracted way to convert between a pair of host name/service name and
42       socket addresses, or vice versa. "getaddrinfo" converts names into a
43       set of arguments to pass to the socket() and connect() syscalls, and
44       "getnameinfo" converts a socket address back into its host name/service
45       name pair.
46
47       These functions provide a useful interface for performing either of
48       these name resolution operation, without having to deal with IPv4/IPv6
49       transparency, or whether the underlying host can support IPv6 at all,
50       or other such issues.  However, not all platforms can support the
51       underlying calls at the C layer, which means a dilema for authors
52       wishing to write forward-compatible code.  Either to support these
53       functions, and cause the code not to work on older platforms, or stick
54       to the older "legacy" resolvers such as gethostbyname(), which means
55       the code becomes more portable.
56
57       This module attempts to solve this problem, by detecting at compiletime
58       whether the underlying OS will support these functions. If it does not,
59       the module will use pure-perl emulations of the functions using the
60       legacy resolver functions instead. The emulations support the same
61       interface as the real functions, and behave as close as is resonably
62       possible to emulate using the legacy resolvers. See
63       Socket::GetAddrInfo::Emul for details on the limits of this emulation.
64
65       As of Perl version 5.14.0, Perl already supports "getaddrinfo" in core.
66       On such a system, this module simply uses the functions provided by
67       "Socket", and does not need to use its own compiled XS, or pure-perl
68       legacy emulation.
69
70       As "Socket" in core now provides all the functions also provided by
71       this module, it is likely this may be the last released version of this
72       module. And code currently using this module would be advised to switch
73       to using core "Socket" instead.
74

EXPORT TAGS

76       The following tags may be imported by "use Socket::GetAddrInfo qw( :tag
77       )":
78
79       AI      Imports all of the "AI_*" constants for "getaddrinfo" flags
80
81       NI      Imports all of the "NI_*" constants for "getnameinfo" flags
82
83       EAI     Imports all of the "EAI_*" for error values
84
85       constants
86               Imports all of the above constants
87

FUNCTIONS

89   ( $err, @res ) = getaddrinfo( $host, $service, $hints )
90       "getaddrinfo" turns human-readable text strings (containing hostnames,
91       numeric addresses, service names, or port numbers) into sets of binary
92       values containing socket-level representations of these addresses.
93
94       When given both host and service, this function attempts to resolve the
95       host name to a set of network addresses, and the service name into a
96       protocol and port number, and then returns a list of address structures
97       suitable to connect() to it.
98
99       When given just a host name, this function attempts to resolve it to a
100       set of network addresses, and then returns a list of these addresses in
101       the returned structures.
102
103       When given just a service name, this function attempts to resolve it to
104       a protocol and port number, and then returns a list of address
105       structures that represent it suitable to bind() to.
106
107       When given neither name, it generates an error.
108
109       The optional $hints parameter can be passed a HASH reference to
110       indicate how the results are generated. It may contain any of the
111       following four fields:
112
113       flags => INT
114               A bitfield containing "AI_*" constants. At least the following
115               flags will be available:
116
117               • "AI_PASSIVE"
118
119                 Indicates that this resolution is for a local bind() for a
120                 passive (i.e.  listening) socket, rather than an active (i.e.
121                 connecting) socket.
122
123               • "AI_CANONNAME"
124
125                 Indicates that the caller wishes the canonical hostname
126                 ("canonname") field of the result to be filled in.
127
128               • "AI_NUMERICHOST"
129
130                 Indicates that the caller will pass a numeric address, rather
131                 than a hostname, and that "getaddrinfo" must not perform a
132                 resolve operation on this name.  This flag will prevent a
133                 possibly-slow network lookup operation, and instead return an
134                 error, if a hostname is passed.
135
136               Other flags may be provided by the OS.
137
138       family => INT
139               Restrict to only generating addresses in this address family
140
141       socktype => INT
142               Restrict to only generating addresses of this socket type
143
144       protocol => INT
145               Restrict to only generating addresses for this protocol
146
147       Errors are indicated by the $err value returned; which will be non-zero
148       in numeric context, and contain a string error message as a string. The
149       value can be compared against any of the "EAI_*" constants to determine
150       what the error is. Rather than explicitly checking, see also
151       Socket::GetAddrInfo::Strict which provides functions that throw
152       exceptions on errors.
153
154       If no error occurs, @res will contain HASH references, each
155       representing one address. It will contain the following five fields:
156
157       family => INT
158               The address family (e.g. AF_INET)
159
160       socktype => INT
161               The socket type (e.g. SOCK_STREAM)
162
163       protocol => INT
164               The protocol (e.g. IPPROTO_TCP)
165
166       addr => STRING
167               The address in a packed string (such as would be returned by
168               pack_sockaddr_in)
169
170       canonname => STRING
171               The canonical name for the host if the "AI_CANONNAME" flag was
172               provided, or "undef" otherwise. This field will only be present
173               on the first returned address.
174
175   ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags )
176       "getnameinfo" turns a binary socket address into a pair of human-
177       readable strings, containing the host name, numeric address, service
178       name, or port number.
179
180       The optional $flags parameter is a bitfield containing "NI_*"
181       constants.  At least the following flags will be available:
182
183       • "NI_NUMERICHOST"
184
185         Requests that a human-readable string representation of the numeric
186         address is returned directly, rather than performing a name resolve
187         operation that may convert it into a hostname.
188
189       • "NI_NUMERICSERV"
190
191         Requests that the port number be returned directly as a number
192         representation rather than performing a name resolve operation that
193         may convert it into a service name.
194
195       • "NI_NAMEREQD"
196
197         If a name resolve operation fails to provide a name, then this flag
198         will cause "getnameinfo" to indicate an error, rather than returning
199         the numeric representation as a human-readable string.
200
201       • "NI_DGRAM"
202
203         Indicates that the socket address relates to a "SOCK_DGRAM" socket,
204         for the services whose name differs between "TCP" and "UDP"
205         protocols.
206
207       Other flags may be provided by the OS.
208
209       The optional $xflags parameter is a bitfield containing "NIx_*"
210       constants.  These are a Perl-level extension to the API, to indicate
211       extra information.
212
213       • "NIx_NOHOST"
214
215         Indicates that the caller is not interested in the hostname of the
216         result, so it does not have to be converted; "undef" will be returned
217         as the hostname.
218
219       • "NIx_NOSERV"
220
221         Indicates that the caller is not interested in the service name of
222         the result, so it does not have to be converted; "undef" will be
223         returned as the service name.
224
225       Errors are indicated by the $err value returned; which will be non-zero
226       in numeric context, and contain a string error message as a string. The
227       value can be compared against any of the "EAI_*" constants to determine
228       what the error is. Rather than explicitly checking, see also
229       Socket::GetAddrInfo::Strict which provides functions that throw
230       exceptions on errors.
231

EXAMPLES

233   Lookup for "connect"
234       The "getaddrinfo" function converts a hostname and a service name into
235       a list of structures, each containing a potential way to connect() to
236       the named service on the named host.
237
238        my %hints = ( socktype => SOCK_STREAM );
239        my ( $err, @res ) = getaddrinfo( $hostname, $servicename, \%hints );
240        die "Cannot getaddrinfo - $err" if $err;
241
242        my $sock;
243
244        foreach my $ai ( @res ) {
245           my $candidate = IO::Socket->new();
246
247           $candidate->socket( $ai->{family}, $ai->{socktype}, $ai->{protocol} )
248              or next;
249
250           $candidate->connect( $ai->{addr} )
251              or next;
252
253           $sock = $candidate;
254           last;
255        }
256
257       Because a list of potential candidates is returned, the "while" loop
258       tries each in turn until it it finds one that succeeds both the
259       socket() and connect() calls.
260
261       This function performs the work of the legacy functions
262       "gethostbyname", "getservbyname", "inet_aton" and "pack_sockaddr_in".
263
264   Making a human-readable string out of an address
265       The "getnameinfo" function converts a socket address, such as returned
266       by "getsockname" or "getpeername", into a pair of human-readable
267       strings representing the address and service name.
268
269        my ( $err, $hostname, $servicename ) = getnameinfo( $socket->peername );
270        die "Cannot getnameinfo - $err" if $err;
271
272        print "The peer is connected from $hostname\n";
273
274       Since in this example only the hostname was used, the redundant
275       conversion of the port number into a service name may be omitted by
276       passing the "NIx_NOSERV" flag.
277
278        my ( $err, $hostname ) = getnameinfo( $socket->peername, 0, NIx_NOSERV );
279
280       This function performs the work of the legacy functions
281       "unpack_sockaddr_in", "inet_ntoa", "gethostbyaddr" and "getservbyport".
282
283   Resolving hostnames into IP addresses
284       To turn a hostname into a human-readable plain IP address use
285       "getaddrinfo" to turn the hostname into a list of socket structures,
286       then "getnameinfo" on each one to make it a readable IP address again.
287
288        my ( $err, @res ) = getaddrinfo( $hostname, "", { socktype => SOCK_RAW } );
289        die "Cannot getaddrinfo - $err" if $err;
290
291        while( my $ai = shift @res ) {
292           my ( $err, $ipaddr ) = getnameinfo( $ai->{addr}, NI_NUMERICHOST, NIx_NOSERV );
293           die "Cannot getnameinfo - $err" if $err;
294
295           print "$ipaddr\n";
296        }
297
298       The "socktype" hint to "getaddrinfo" filters the results to only
299       include one socket type and protocol. Without this most OSes return
300       three combinations, for "SOCK_STREAM", "SOCK_DGRAM" and "SOCK_RAW",
301       resulting in triplicate output of addresses. The "NI_NUMERICHOST" flag
302       to "getnameinfo" causes it to return a string-formatted plain IP
303       address, rather than reverse resolving it back into a hostname.
304
305       This combination performs the work of the legacy functions
306       "gethostbyname" and "inet_ntoa".
307

BUILDING WITHOUT XS CODE

309       In some environments it may be preferred not to build the XS
310       implementation, leaving a choice only of the core or pure-perl
311       emulation implementations.
312
313        $ perl Build.PL --pp
314
315       or
316
317        $ PERL_SOCKET_GETADDRINFO_NO_BUILD_XS=1 perl Build.PL
318

BUGS

320       •   Appears to FAIL on older Darwin machines (e.g. "osvers=8.11.1").
321           The failure mode occurs in t/02getnameinfo.t and appears to relate
322           to an endian bug; expecting to receive 80 and instead receiving
323           20480 (which is a 16-bit 80 byte-swapped).
324

SEE ALSO

326       •   <http://tools.ietf.org/html/rfc2553> - Basic Socket Interface
327           Extensions for IPv6
328

ACKNOWLEDGEMENTS

330       Christian Hansen <chansen@cpan.org> - for help with some XS features
331       and Win32 build fixes.
332
333       Zefram <zefram@fysh.org> - for help with fixing some bugs in the XS
334       code.
335
336       Reini Urban <rurban@cpan.org> - for help with older perls and more
337       Win32 build fixes.
338

AUTHOR

340       Paul Evans <leonerd@leonerd.org.uk>
341
342
343
344perl v5.36.0                      2023-01-20            Socket::GetAddrInfo(3)
Impressum