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(): _POSIX_C_SOURCE >= 1 ||
25 _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 getservbyname(3) and getservbyport(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 size_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 logically 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 only
157 returned if the local system has at least one IPv6 address configured.
158
159 If hint.ai_flags specifies the AI_V4MAPPED flag, and hints.ai_family
160 was specified as AF_INET6, and no matching IPv6 addresses could be
161 found, then return IPv4-mapped IPv6 addresses in the list pointed to by
162 res. If both AI_V4MAPPED and AI_ALL are specified in hints.ai_flags,
163 then return both IPv6 and IPv4-mapped IPv6 addresses in the list
164 pointed to by res. AI_ALL is ignored if AI_V4MAPPED is not also speci‐
165 fied.
166
167 The freeaddrinfo() function frees the memory that was allocated for the
168 dynamically allocated linked list res.
169
170 Extensions to getaddrinfo() for Internationalized Domain Names
171 Starting with glibc 2.3.4, getaddrinfo() has been extended to selec‐
172 tively allow the incoming and outgoing hostnames to be transparently
173 converted to and from the Internationalized Domain Name (IDN) format
174 (see RFC 3490, Internationalizing Domain Names in Applications (IDNA)).
175 Four new flags are defined:
176
177 AI_IDN If this flag is specified, then the node name given in node is
178 converted to IDN format if necessary. The source encoding is
179 that of the current locale.
180
181 If the input name contains non-ASCII characters, then the IDN
182 encoding is used. Those parts of the node name (delimited by
183 dots) that contain non-ASCII characters are encoded using ASCII
184 Compatible Encoding (ACE) before being passed to the name reso‐
185 lution functions.
186
187 AI_CANONIDN
188 After a successful name lookup, and if the AI_CANONNAME flag was
189 specified, getaddrinfo() will return the canonical name of the
190 node corresponding to the addrinfo structure value passed back.
191 The return value is an exact copy of the value returned by the
192 name resolution function.
193
194 If the name is encoded using ACE, then it will contain the xn--
195 prefix for one or more components of the name. To convert these
196 components into a readable form the AI_CANONIDN flag can be
197 passed in addition to AI_CANONNAME. The resulting string is
198 encoded using the current locale's encoding.
199
200 AI_IDN_ALLOW_UNASSIGNED, AI_IDN_USE_STD3_ASCII_RULES
201 Setting these flags will enable the IDNA_ALLOW_UNASSIGNED (allow
202 unassigned Unicode code points) and IDNA_USE_STD3_ASCII_RULES
203 (check output to make sure it is a STD3 conforming hostname)
204 flags respectively to be used in the IDNA handling.
205
207 getaddrinfo() returns 0 if it succeeds, or one of the following nonzero
208 error codes:
209
210 EAI_ADDRFAMILY
211 The specified network host does not have any network addresses
212 in the requested address family.
213
214 EAI_AGAIN
215 The name server returned a temporary failure indication. Try
216 again later.
217
218 EAI_BADFLAGS
219 hints.ai_flags contains invalid flags; or, hints.ai_flags
220 included AI_CANONNAME and name was NULL.
221
222 EAI_FAIL
223 The name server returned a permanent failure indication.
224
225 EAI_FAMILY
226 The requested address family is not supported.
227
228 EAI_MEMORY
229 Out of memory.
230
231 EAI_NODATA
232 The specified network host exists, but does not have any network
233 addresses defined.
234
235 EAI_NONAME
236 The node or service is not known; or both node and service are
237 NULL; or AI_NUMERICSERV was specified in hints.ai_flags and ser‐
238 vice was not a numeric port-number string.
239
240 EAI_SERVICE
241 The requested service is not available for the requested socket
242 type. It may be available through another socket type. For
243 example, this error could occur if service was "shell" (a ser‐
244 vice only available on stream sockets), and either hints.ai_pro‐
245 tocol was IPPROTO_UDP, or hints.ai_socktype was SOCK_DGRAM; or
246 the error could occur if service was not NULL, and
247 hints.ai_socktype was SOCK_RAW (a socket type that does not sup‐
248 port the concept of services).
249
250 EAI_SOCKTYPE
251 The requested socket type is not supported. This could occur,
252 for example, if hints.ai_socktype and hints.ai_protocol are
253 inconsistent (e.g., SOCK_DGRAM and IPPROTO_TCP, respectively).
254
255 EAI_SYSTEM
256 Other system error, check errno for details.
257
258 The gai_strerror() function translates these error codes to a human
259 readable string, suitable for error reporting.
260
262 /etc/gai.conf
263
265 POSIX.1-2001. The getaddrinfo() function is documented in RFC 2553.
266
268 getaddrinfo() supports the address%scope-id notation for specifying the
269 IPv6 scope-ID.
270
271 AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3.
272 AI_NUMERICSERV is available since glibc 2.3.4.
273
274 According to POSIX.1-2001, specifying hints as NULL should cause
275 ai_flags to be assumed as 0. The GNU C library instead assumes a value
276 of (AI_V4MAPPED | AI_ADDRCONFIG) for this case, since this value is
277 considered an improvement on the specification.
278
280 The following programs demonstrate the use of getaddrinfo(), gai_str‐
281 error(), freeaddrinfo(), and getnameinfo(3). The programs are an echo
282 server and client for UDP datagrams.
283
284 Server program
285
286 #include <sys/types.h>
287 #include <stdio.h>
288 #include <stdlib.h>
289 #include <unistd.h>
290 #include <string.h>
291 #include <sys/socket.h>
292 #include <netdb.h>
293
294 #define BUF_SIZE 500
295
296 int
297 main(int argc, char *argv[])
298 {
299 struct addrinfo hints;
300 struct addrinfo *result, *rp;
301 int sfd, s;
302 struct sockaddr_storage peer_addr;
303 socklen_t peer_addr_len;
304 ssize_t nread;
305 char buf[BUF_SIZE];
306
307 if (argc != 2) {
308 fprintf(stderr, "Usage: %s port\n", argv[0]);
309 exit(EXIT_FAILURE);
310 }
311
312 memset(&hints, 0, sizeof(struct addrinfo));
313 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
314 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
315 hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
316 hints.ai_protocol = 0; /* Any protocol */
317 hints.ai_canonname = NULL;
318 hints.ai_addr = NULL;
319 hints.ai_next = NULL;
320
321 s = getaddrinfo(NULL, argv[1], &hints, &result);
322 if (s != 0) {
323 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
324 exit(EXIT_FAILURE);
325 }
326
327 /* getaddrinfo() returns a list of address structures.
328 Try each address until we successfully bind(2).
329 If socket(2) (or bind(2)) fails, we (close the socket
330 and) try the next address. */
331
332 for (rp = result; rp != NULL; rp = rp->ai_next) {
333 sfd = socket(rp->ai_family, rp->ai_socktype,
334 rp->ai_protocol);
335 if (sfd == -1)
336 continue;
337
338 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
339 break; /* Success */
340
341 close(sfd);
342 }
343
344 if (rp == NULL) { /* No address succeeded */
345 fprintf(stderr, "Could not bind\n");
346 exit(EXIT_FAILURE);
347 }
348
349 freeaddrinfo(result); /* No longer needed */
350
351 /* Read datagrams and echo them back to sender */
352
353 for (;;) {
354 peer_addr_len = sizeof(struct sockaddr_storage);
355 nread = recvfrom(sfd, buf, BUF_SIZE, 0,
356 (struct sockaddr *) &peer_addr, &peer_addr_len);
357 if (nread == -1)
358 continue; /* Ignore failed request */
359
360 char host[NI_MAXHOST], service[NI_MAXSERV];
361
362 s = getnameinfo((struct sockaddr *) &peer_addr,
363 peer_addr_len, host, NI_MAXHOST,
364 service, NI_MAXSERV, NI_NUMERICSERV);
365 if (s == 0)
366 printf("Received %ld bytes from %s:%s\n",
367 (long) nread, host, service);
368 else
369 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
370
371 if (sendto(sfd, buf, nread, 0,
372 (struct sockaddr *) &peer_addr,
373 peer_addr_len) != nread)
374 fprintf(stderr, "Error sending response\n");
375 }
376 }
377
378 Client program
379
380 #include <sys/types.h>
381 #include <sys/socket.h>
382 #include <netdb.h>
383 #include <stdio.h>
384 #include <stdlib.h>
385 #include <unistd.h>
386 #include <string.h>
387
388 #define BUF_SIZE 500
389
390 int
391 main(int argc, char *argv[])
392 {
393 struct addrinfo hints;
394 struct addrinfo *result, *rp;
395 int sfd, s, j;
396 size_t len;
397 ssize_t nread;
398 char buf[BUF_SIZE];
399
400 if (argc < 3) {
401 fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
402 exit(EXIT_FAILURE);
403 }
404
405 /* Obtain address(es) matching host/port */
406
407 memset(&hints, 0, sizeof(struct addrinfo));
408 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
409 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
410 hints.ai_flags = 0;
411 hints.ai_protocol = 0; /* Any protocol */
412
413 s = getaddrinfo(argv[1], argv[2], &hints, &result);
414 if (s != 0) {
415 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
416 exit(EXIT_FAILURE);
417 }
418
419 /* getaddrinfo() returns a list of address structures.
420 Try each address until we successfully connect(2).
421 If socket(2) (or connect(2)) fails, we (close the socket
422 and) try the next address. */
423
424 for (rp = result; rp != NULL; rp = rp->ai_next) {
425 sfd = socket(rp->ai_family, rp->ai_socktype,
426 rp->ai_protocol);
427 if (sfd == -1)
428 continue;
429
430 if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
431 break; /* Success */
432
433 close(sfd);
434 }
435
436 if (rp == NULL) { /* No address succeeded */
437 fprintf(stderr, "Could not connect\n");
438 exit(EXIT_FAILURE);
439 }
440
441 freeaddrinfo(result); /* No longer needed */
442
443 /* Send remaining command-line arguments as separate
444 datagrams, and read responses from server */
445
446 for (j = 3; j < argc; j++) {
447 len = strlen(argv[j]) + 1;
448 /* +1 for terminating null byte */
449
450 if (len + 1 > BUF_SIZE) {
451 fprintf(stderr,
452 "Ignoring long message in argument %d\n", j);
453 continue;
454 }
455
456 if (write(sfd, argv[j], len) != len) {
457 fprintf(stderr, "partial/failed write\n");
458 exit(EXIT_FAILURE);
459 }
460
461 nread = read(sfd, buf, BUF_SIZE);
462 if (nread == -1) {
463 perror("read");
464 exit(EXIT_FAILURE);
465 }
466
467 printf("Received %ld bytes: %s\n", (long) nread, buf);
468 }
469
470 exit(EXIT_SUCCESS);
471 }
472
474 gethostbyname(3), getnameinfo(3), inet(3), hostname(7), ip(7)
475
477 This page is part of release 3.25 of the Linux man-pages project. A
478 description of the project, and information about reporting bugs, can
479 be found at http://www.kernel.org/doc/man-pages/.
480
481
482
483GNU 2010-06-17 GETADDRINFO(3)