1GETADDRINFO(3) Linux Programmer's Manual GETADDRINFO(3)
2
3
4
6 getaddrinfo, freeaddrinfo, gai_strerror - network address and service
7 translation
8
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netdb.h>
13
14 int getaddrinfo(const char *node, const char *service,
15 const struct addrinfo *hints,
16 struct addrinfo **res);
17
18 void freeaddrinfo(struct addrinfo *res);
19
20 const char *gai_strerror(int errcode);
21
22 Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
23
24 getaddrinfo(), freeaddrinfo(), gai_strerror():
25 _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
26
28 Given node and service, which identify an Internet host and a service,
29 getaddrinfo() returns one or more addrinfo structures, each of which
30 contains an Internet address that can be specified in a call to bind(2)
31 or connect(2). The getaddrinfo() function combines the functionality
32 provided by the gethostbyname(3) and getservbyname(3) functions into a
33 single interface, but unlike the latter functions, getaddrinfo() is
34 reentrant and allows programs to eliminate IPv4-versus-IPv6 dependen‐
35 cies.
36
37 The addrinfo structure used by getaddrinfo() contains the following
38 fields:
39
40 struct addrinfo {
41 int ai_flags;
42 int ai_family;
43 int ai_socktype;
44 int ai_protocol;
45 socklen_t ai_addrlen;
46 struct sockaddr *ai_addr;
47 char *ai_canonname;
48 struct addrinfo *ai_next;
49 };
50
51 The hints argument points to an addrinfo structure that specifies cri‐
52 teria for selecting the socket address structures returned in the list
53 pointed to by res. If hints is not NULL it points to an addrinfo
54 structure whose ai_family, ai_socktype, and ai_protocol specify crite‐
55 ria that limit the set of socket addresses returned by getaddrinfo(),
56 as follows:
57
58 ai_family This field specifies the desired address family for the
59 returned addresses. Valid values for this field include
60 AF_INET and AF_INET6. The value AF_UNSPEC indicates that
61 getaddrinfo() should return socket addresses for any
62 address family (either IPv4 or IPv6, for example) that can
63 be used with node and service.
64
65 ai_socktype This field specifies the preferred socket type, for example
66 SOCK_STREAM or SOCK_DGRAM. Specifying 0 in this field
67 indicates that socket addresses of any type can be returned
68 by getaddrinfo().
69
70 ai_protocol This field specifies the protocol for the returned socket
71 addresses. Specifying 0 in this field indicates that
72 socket addresses with any protocol can be returned by
73 getaddrinfo().
74
75 ai_flags This field specifies additional options, described below.
76 Multiple flags are specified by bitwise OR-ing them
77 together.
78
79 All the other fields in the structure pointed to by hints must contain
80 either 0 or a NULL pointer, as appropriate. Specifying hints as NULL
81 is equivalent to setting ai_socktype and ai_protocol to 0; ai_family to
82 AF_UNSPEC; and ai_flags to (AI_V4MAPPED | AI_ADDRCONFIG).
83
84 node specifies either a numerical network address (for IPv4, numbers-
85 and-dots notation as supported by inet_aton(3); for IPv6, hexadecimal
86 string format as supported by inet_pton(3)), or a network hostname,
87 whose network addresses are looked up and resolved. If hints.ai_flags
88 contains the AI_NUMERICHOST flag then node must be a numerical network
89 address. The AI_NUMERICHOST flag suppresses any potentially lengthy
90 network host address lookups.
91
92 If the AI_PASSIVE flag is specified in hints.ai_flags, and node is
93 NULL, then the returned socket addresses will be suitable for
94 bind(2)ing a socket that will accept(2) connections. The returned
95 socket address will contain the "wildcard address" (INADDR_ANY for IPv4
96 addresses, IN6ADDR_ANY_INIT for IPv6 address). The wildcard address is
97 used by applications (typically servers) that intend to accept connec‐
98 tions on any of the hosts's network addresses. If node is not NULL,
99 then the AI_PASSIVE flag is ignored.
100
101 If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned
102 socket addresses will be suitable for use with connect(2), sendto(2),
103 or sendmsg(2). If node is NULL, then the network address will be set
104 to the loopback interface address (INADDR_LOOPBACK for IPv4 addresses,
105 IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications
106 that intend to communicate with peers running on the same host.
107
108 service sets the port in each returned address structure. If this
109 argument is a service name (see services(5)), it is translated to the
110 corresponding port number. This argument can also be specified as a
111 decimal number, which is simply converted to binary. If service is
112 NULL, then the port number of the returned socket addresses will be
113 left uninitialized. If AI_NUMERICSERV is specified in hints.ai_flags
114 and service is not NULL, then service must point to a string containing
115 a numeric port number. This flag is used to inhibit the invocation of
116 a name resolution service in cases where it is known not to be
117 required.
118
119 Either node or service, but not both, may be NULL.
120
121 The getaddrinfo() function allocates and initializes a linked list of
122 addrinfo structures, one for each network address that matches node and
123 service, subject to any restrictions imposed by hints, and returns a
124 pointer to the start of the list in res. The items in the linked list
125 are linked by the ai_next field.
126
127 There are several reasons why the linked list may have more than one
128 addrinfo structure, including: the network host is multihomed, accessi‐
129 ble over multiple protocols (e.g., both AF_INET and AF_INET6); or the
130 same service is available from multiple socket types (one SOCK_STREAM
131 address and another SOCK_DGRAM address, for example). Normally, the
132 application should try using the addresses in the order in which they
133 are returned. The sorting function used within getaddrinfo() is
134 defined in RFC 3484; the order can be tweaked for a particular system
135 by editing /etc/gai.conf (available since glibc 2.5).
136
137 If hints.ai_flags includes the AI_CANONNAME flag, then the ai_canonname
138 field of the first of the addrinfo structures in the returned list is
139 set to point to the official name of the host.
140
141 The remaining fields of each returned addrinfo structure are initial‐
142 ized as follows:
143
144 * The ai_family, ai_socktype, and ai_protocol fields return the socket
145 creation parameters (i.e., these fields have the same meaning as the
146 corresponding arguments of socket(2)). For example, ai_family might
147 return AF_INET or AF_INET6; ai_socktype might return SOCK_DGRAM or
148 SOCK_STREAM; and ai_protocol returns the protocol for the socket.
149
150 * A pointer to the socket address is placed in the ai_addr field, and
151 the length of the socket address, in bytes, is placed in the
152 ai_addrlen field.
153
154 If hints.ai_flags includes the AI_ADDRCONFIG flag, then IPv4 addresses
155 are returned in the list pointed to by res only if the local system has
156 at least one IPv4 address configured, and IPv6 addresses are returned
157 only if the local system has at least one IPv6 address configured. The
158 loopback address is not considered for this case as valid as a config‐
159 ured address.
160
161 If hints.ai_flags specifies the AI_V4MAPPED flag, and hints.ai_family
162 was specified as AF_INET6, and no matching IPv6 addresses could be
163 found, then return IPv4-mapped IPv6 addresses in the list pointed to by
164 res. If both AI_V4MAPPED and AI_ALL are specified in hints.ai_flags,
165 then return both IPv6 and IPv4-mapped IPv6 addresses in the list
166 pointed to by res. AI_ALL is ignored if AI_V4MAPPED is not also speci‐
167 fied.
168
169 The freeaddrinfo() function frees the memory that was allocated for the
170 dynamically allocated linked list res.
171
172 Extensions to getaddrinfo() for Internationalized Domain Names
173 Starting with glibc 2.3.4, getaddrinfo() has been extended to selec‐
174 tively allow the incoming and outgoing hostnames to be transparently
175 converted to and from the Internationalized Domain Name (IDN) format
176 (see RFC 3490, Internationalizing Domain Names in Applications (IDNA)).
177 Four new flags are defined:
178
179 AI_IDN If this flag is specified, then the node name given in node is
180 converted to IDN format if necessary. The source encoding is
181 that of the current locale.
182
183 If the input name contains non-ASCII characters, then the IDN
184 encoding is used. Those parts of the node name (delimited by
185 dots) that contain non-ASCII characters are encoded using ASCII
186 Compatible Encoding (ACE) before being passed to the name reso‐
187 lution functions.
188
189 AI_CANONIDN
190 After a successful name lookup, and if the AI_CANONNAME flag was
191 specified, getaddrinfo() will return the canonical name of the
192 node corresponding to the addrinfo structure value passed back.
193 The return value is an exact copy of the value returned by the
194 name resolution function.
195
196 If the name is encoded using ACE, then it will contain the xn--
197 prefix for one or more components of the name. To convert these
198 components into a readable form the AI_CANONIDN flag can be
199 passed in addition to AI_CANONNAME. The resulting string is
200 encoded using the current locale's encoding.
201
202 AI_IDN_ALLOW_UNASSIGNED, AI_IDN_USE_STD3_ASCII_RULES
203 Setting these flags will enable the IDNA_ALLOW_UNASSIGNED (allow
204 unassigned Unicode code points) and IDNA_USE_STD3_ASCII_RULES
205 (check output to make sure it is a STD3 conforming hostname)
206 flags respectively to be used in the IDNA handling.
207
209 getaddrinfo() returns 0 if it succeeds, or one of the following nonzero
210 error codes:
211
212 EAI_ADDRFAMILY
213 The specified network host does not have any network addresses
214 in the requested address family.
215
216 EAI_AGAIN
217 The name server returned a temporary failure indication. Try
218 again later.
219
220 EAI_BADFLAGS
221 hints.ai_flags contains invalid flags; or, hints.ai_flags
222 included AI_CANONNAME and name was NULL.
223
224 EAI_FAIL
225 The name server returned a permanent failure indication.
226
227 EAI_FAMILY
228 The requested address family is not supported.
229
230 EAI_MEMORY
231 Out of memory.
232
233 EAI_NODATA
234 The specified network host exists, but does not have any network
235 addresses defined.
236
237 EAI_NONAME
238 The node or service is not known; or both node and service are
239 NULL; or AI_NUMERICSERV was specified in hints.ai_flags and ser‐
240 vice was not a numeric port-number string.
241
242 EAI_SERVICE
243 The requested service is not available for the requested socket
244 type. It may be available through another socket type. For
245 example, this error could occur if service was "shell" (a ser‐
246 vice available only on stream sockets), and either hints.ai_pro‐
247 tocol was IPPROTO_UDP, or hints.ai_socktype was SOCK_DGRAM; or
248 the error could occur if service was not NULL, and
249 hints.ai_socktype was SOCK_RAW (a socket type that does not sup‐
250 port the concept of services).
251
252 EAI_SOCKTYPE
253 The requested socket type is not supported. This could occur,
254 for example, if hints.ai_socktype and hints.ai_protocol are
255 inconsistent (e.g., SOCK_DGRAM and IPPROTO_TCP, respectively).
256
257 EAI_SYSTEM
258 Other system error, check errno for details.
259
260 The gai_strerror() function translates these error codes to a human
261 readable string, suitable for error reporting.
262
264 /etc/gai.conf
265
267 POSIX.1-2001. The getaddrinfo() function is documented in RFC 2553.
268
270 getaddrinfo() supports the address%scope-id notation for specifying the
271 IPv6 scope-ID.
272
273 AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3.
274 AI_NUMERICSERV is available since glibc 2.3.4.
275
276 According to POSIX.1-2001, specifying hints as NULL should cause
277 ai_flags to be assumed as 0. The GNU C library instead assumes a value
278 of (AI_V4MAPPED | AI_ADDRCONFIG) for this case, since this value is
279 considered an improvement on the specification.
280
282 The following programs demonstrate the use of getaddrinfo(), gai_str‐
283 error(), freeaddrinfo(), and getnameinfo(3). The programs are an echo
284 server and client for UDP datagrams.
285
286 Server program
287
288 #include <sys/types.h>
289 #include <stdio.h>
290 #include <stdlib.h>
291 #include <unistd.h>
292 #include <string.h>
293 #include <sys/socket.h>
294 #include <netdb.h>
295
296 #define BUF_SIZE 500
297
298 int
299 main(int argc, char *argv[])
300 {
301 struct addrinfo hints;
302 struct addrinfo *result, *rp;
303 int sfd, s;
304 struct sockaddr_storage peer_addr;
305 socklen_t peer_addr_len;
306 ssize_t nread;
307 char buf[BUF_SIZE];
308
309 if (argc != 2) {
310 fprintf(stderr, "Usage: %s port\n", argv[0]);
311 exit(EXIT_FAILURE);
312 }
313
314 memset(&hints, 0, sizeof(struct addrinfo));
315 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
316 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
317 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
318 hints.ai_protocol = 0; /* Any protocol */
319 hints.ai_canonname = NULL;
320 hints.ai_addr = NULL;
321 hints.ai_next = NULL;
322
323 s = getaddrinfo(NULL, argv[1], &hints, &result);
324 if (s != 0) {
325 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
326 exit(EXIT_FAILURE);
327 }
328
329 /* getaddrinfo() returns a list of address structures.
330 Try each address until we successfully bind(2).
331 If socket(2) (or bind(2)) fails, we (close the socket
332 and) try the next address. */
333
334 for (rp = result; rp != NULL; rp = rp->ai_next) {
335 sfd = socket(rp->ai_family, rp->ai_socktype,
336 rp->ai_protocol);
337 if (sfd == -1)
338 continue;
339
340 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
341 break; /* Success */
342
343 close(sfd);
344 }
345
346 if (rp == NULL) { /* No address succeeded */
347 fprintf(stderr, "Could not bind\n");
348 exit(EXIT_FAILURE);
349 }
350
351 freeaddrinfo(result); /* No longer needed */
352
353 /* Read datagrams and echo them back to sender */
354
355 for (;;) {
356 peer_addr_len = sizeof(struct sockaddr_storage);
357 nread = recvfrom(sfd, buf, BUF_SIZE, 0,
358 (struct sockaddr *) &peer_addr, &peer_addr_len);
359 if (nread == -1)
360 continue; /* Ignore failed request */
361
362 char host[NI_MAXHOST], service[NI_MAXSERV];
363
364 s = getnameinfo((struct sockaddr *) &peer_addr,
365 peer_addr_len, host, NI_MAXHOST,
366 service, NI_MAXSERV, NI_NUMERICSERV);
367 if (s == 0)
368 printf("Received %ld bytes from %s:%s\n",
369 (long) nread, host, service);
370 else
371 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
372
373 if (sendto(sfd, buf, nread, 0,
374 (struct sockaddr *) &peer_addr,
375 peer_addr_len) != nread)
376 fprintf(stderr, "Error sending response\n");
377 }
378 }
379
380 Client program
381
382 #include <sys/types.h>
383 #include <sys/socket.h>
384 #include <netdb.h>
385 #include <stdio.h>
386 #include <stdlib.h>
387 #include <unistd.h>
388 #include <string.h>
389
390 #define BUF_SIZE 500
391
392 int
393 main(int argc, char *argv[])
394 {
395 struct addrinfo hints;
396 struct addrinfo *result, *rp;
397 int sfd, s, j;
398 size_t len;
399 ssize_t nread;
400 char buf[BUF_SIZE];
401
402 if (argc < 3) {
403 fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
404 exit(EXIT_FAILURE);
405 }
406
407 /* Obtain address(es) matching host/port */
408
409 memset(&hints, 0, sizeof(struct addrinfo));
410 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
411 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
412 hints.ai_flags = 0;
413 hints.ai_protocol = 0; /* Any protocol */
414
415 s = getaddrinfo(argv[1], argv[2], &hints, &result);
416 if (s != 0) {
417 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
418 exit(EXIT_FAILURE);
419 }
420
421 /* getaddrinfo() returns a list of address structures.
422 Try each address until we successfully connect(2).
423 If socket(2) (or connect(2)) fails, we (close the socket
424 and) try the next address. */
425
426 for (rp = result; rp != NULL; rp = rp->ai_next) {
427 sfd = socket(rp->ai_family, rp->ai_socktype,
428 rp->ai_protocol);
429 if (sfd == -1)
430 continue;
431
432 if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
433 break; /* Success */
434
435 close(sfd);
436 }
437
438 if (rp == NULL) { /* No address succeeded */
439 fprintf(stderr, "Could not connect\n");
440 exit(EXIT_FAILURE);
441 }
442
443 freeaddrinfo(result); /* No longer needed */
444
445 /* Send remaining command-line arguments as separate
446 datagrams, and read responses from server */
447
448 for (j = 3; j < argc; j++) {
449 len = strlen(argv[j]) + 1;
450 /* +1 for terminating null byte */
451
452 if (len + 1 > BUF_SIZE) {
453 fprintf(stderr,
454 "Ignoring long message in argument %d\n", j);
455 continue;
456 }
457
458 if (write(sfd, argv[j], len) != len) {
459 fprintf(stderr, "partial/failed write\n");
460 exit(EXIT_FAILURE);
461 }
462
463 nread = read(sfd, buf, BUF_SIZE);
464 if (nread == -1) {
465 perror("read");
466 exit(EXIT_FAILURE);
467 }
468
469 printf("Received %ld bytes: %s\n", (long) nread, buf);
470 }
471
472 exit(EXIT_SUCCESS);
473 }
474
476 getaddrinfo_a(3), gethostbyname(3), getnameinfo(3), inet(3),
477 gai.conf(5), hostname(7), ip(7)
478
480 This page is part of release 3.53 of the Linux man-pages project. A
481 description of the project, and information about reporting bugs, can
482 be found at http://www.kernel.org/doc/man-pages/.
483
484
485
486GNU 2013-01-15 GETADDRINFO(3)