1GETADDRINFO(3)             Linux Programmer's Manual            GETADDRINFO(3)
2
3
4

NAME

6       getaddrinfo,  freeaddrinfo,  gai_strerror - network address and service
7       translation
8

SYNOPSIS

10       #include <sys/types.h>
11       #include <sys/socket.h>
12       #include <netdb.h>
13
14       int getaddrinfo(const char *restrict node,
15                       const char *restrict service,
16                       const struct addrinfo *restrict hints,
17                       struct addrinfo **restrict res);
18
19       void freeaddrinfo(struct addrinfo *res);
20
21       const char *gai_strerror(int errcode);
22
23   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
24
25       getaddrinfo(), freeaddrinfo(), gai_strerror():
26           Since glibc 2.22:
27               _POSIX_C_SOURCE >= 200112L
28           Glibc 2.21 and earlier:
29               _POSIX_C_SOURCE
30

DESCRIPTION

32       Given node and service, which identify an Internet host and a  service,
33       getaddrinfo()  returns  one  or more addrinfo structures, each of which
34       contains an Internet address that can be specified in a call to bind(2)
35       or  connect(2).   The getaddrinfo() function combines the functionality
36       provided by the gethostbyname(3) and getservbyname(3) functions into  a
37       single  interface,  but  unlike  the latter functions, getaddrinfo() is
38       reentrant and allows programs to eliminate  IPv4-versus-IPv6  dependen‐
39       cies.
40
41       The  addrinfo  structure  used  by getaddrinfo() contains the following
42       fields:
43
44           struct addrinfo {
45               int              ai_flags;
46               int              ai_family;
47               int              ai_socktype;
48               int              ai_protocol;
49               socklen_t        ai_addrlen;
50               struct sockaddr *ai_addr;
51               char            *ai_canonname;
52               struct addrinfo *ai_next;
53           };
54
55       The hints argument points to an addrinfo structure that specifies  cri‐
56       teria  for selecting the socket address structures returned in the list
57       pointed to by res.  If hints is not  NULL  it  points  to  an  addrinfo
58       structure  whose ai_family, ai_socktype, and ai_protocol specify crite‐
59       ria that limit the set of socket addresses returned  by  getaddrinfo(),
60       as follows:
61
62       ai_family
63              This field specifies the desired address family for the returned
64              addresses.  Valid values for  this  field  include  AF_INET  and
65              AF_INET6.   The  value  AF_UNSPEC  indicates  that getaddrinfo()
66              should return socket addresses for any  address  family  (either
67              IPv4  or  IPv6, for example) that can be used with node and ser‐
68              vice.
69
70       ai_socktype
71              This field specifies the  preferred  socket  type,  for  example
72              SOCK_STREAM or SOCK_DGRAM.  Specifying 0 in this field indicates
73              that socket addresses of any type  can  be  returned  by  getad‐
74              drinfo().
75
76       ai_protocol
77              This  field  specifies  the protocol for the returned socket ad‐
78              dresses.  Specifying 0 in this field indicates that  socket  ad‐
79              dresses with any protocol can be returned by getaddrinfo().
80
81       ai_flags
82              This  field specifies additional options, described below.  Mul‐
83              tiple flags are specified by bitwise OR-ing them together.
84
85       All the other fields in the structure pointed to by hints must  contain
86       either 0 or a null pointer, as appropriate.
87
88       Specifying  hints  as  NULL  is  equivalent  to setting ai_socktype and
89       ai_protocol  to  0;   ai_family   to   AF_UNSPEC;   and   ai_flags   to
90       (AI_V4MAPPED | AI_ADDRCONFIG).  (POSIX specifies different defaults for
91       ai_flags; see NOTES.)  node specifies either a  numerical  network  ad‐
92       dress   (for   IPv4,   numbers-and-dots   notation   as   supported  by
93       inet_aton(3); for IPv6,  hexadecimal  string  format  as  supported  by
94       inet_pton(3)),  or  a  network  hostname,  whose  network addresses are
95       looked up and resolved.  If hints.ai_flags contains the  AI_NUMERICHOST
96       flag,  then  node  must be a numerical network address.  The AI_NUMERI‐
97       CHOST flag suppresses any  potentially  lengthy  network  host  address
98       lookups.
99
100       If  the  AI_PASSIVE  flag  is  specified in hints.ai_flags, and node is
101       NULL,  then  the  returned  socket  addresses  will  be  suitable   for
102       bind(2)ing  a  socket  that  will  accept(2) connections.  The returned
103       socket address will contain the "wildcard address" (INADDR_ANY for IPv4
104       addresses, IN6ADDR_ANY_INIT for IPv6 address).  The wildcard address is
105       used by applications (typically servers) that intend to accept  connec‐
106       tions  on  any  of  the host's network addresses.  If node is not NULL,
107       then the AI_PASSIVE flag is ignored.
108
109       If the AI_PASSIVE flag is not set in hints.ai_flags, then the  returned
110       socket  addresses  will be suitable for use with connect(2), sendto(2),
111       or sendmsg(2).  If node is NULL, then the network address will  be  set
112       to  the loopback interface address (INADDR_LOOPBACK for IPv4 addresses,
113       IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used  by  applications
114       that intend to communicate with peers running on the same host.
115
116       service  sets the port in each returned address structure.  If this ar‐
117       gument is a service name (see services(5)), it  is  translated  to  the
118       corresponding  port  number.   This argument can also be specified as a
119       decimal number, which is simply converted to  binary.   If  service  is
120       NULL,  then  the  port  number of the returned socket addresses will be
121       left uninitialized.  If AI_NUMERICSERV is specified  in  hints.ai_flags
122       and service is not NULL, then service must point to a string containing
123       a numeric port number.  This flag is used to inhibit the invocation  of
124       a  name  resolution  service  in  cases where it is known not to be re‐
125       quired.
126
127       Either node or service, but not both, may be NULL.
128
129       The getaddrinfo() function allocates and initializes a linked  list  of
130       addrinfo structures, one for each network address that matches node and
131       service, subject to any restrictions imposed by hints,  and  returns  a
132       pointer  to the start of the list in res.  The items in the linked list
133       are linked by the ai_next field.
134
135       There are several reasons why the linked list may have  more  than  one
136       addrinfo structure, including: the network host is multihomed, accessi‐
137       ble over multiple protocols (e.g., both AF_INET and AF_INET6);  or  the
138       same  service  is available from multiple socket types (one SOCK_STREAM
139       address and another SOCK_DGRAM address, for  example).   Normally,  the
140       application  should  try using the addresses in the order in which they
141       are returned.  The sorting function used within  getaddrinfo()  is  de‐
142       fined  in RFC 3484; the order can be tweaked for a particular system by
143       editing /etc/gai.conf (available since glibc 2.5).
144
145       If hints.ai_flags includes the AI_CANONNAME flag, then the ai_canonname
146       field  of  the first of the addrinfo structures in the returned list is
147       set to point to the official name of the host.
148
149       The remaining fields of each returned addrinfo structure  are  initial‐
150       ized as follows:
151
152       * The  ai_family, ai_socktype, and ai_protocol fields return the socket
153         creation parameters (i.e., these fields have the same meaning as  the
154         corresponding  arguments of socket(2)).  For example, ai_family might
155         return AF_INET or AF_INET6; ai_socktype might  return  SOCK_DGRAM  or
156         SOCK_STREAM; and ai_protocol returns the protocol for the socket.
157
158       * A  pointer  to the socket address is placed in the ai_addr field, and
159         the length of the socket address, in bytes, is placed in  the  ai_ad‐
160         drlen field.
161
162       If  hints.ai_flags includes the AI_ADDRCONFIG flag, then IPv4 addresses
163       are returned in the list pointed to by res only if the local system has
164       at  least  one IPv4 address configured, and IPv6 addresses are returned
165       only if the local system has at least one IPv6 address configured.  The
166       loopback  address is not considered for this case as valid as a config‐
167       ured address.  This flag is useful on, for example, IPv4-only  systems,
168       to ensure that getaddrinfo() does not return IPv6 socket addresses that
169       would always fail in connect(2) or bind(2).
170
171       If hints.ai_flags specifies the AI_V4MAPPED flag,  and  hints.ai_family
172       was  specified  as  AF_INET6,  and  no matching IPv6 addresses could be
173       found, then return IPv4-mapped IPv6 addresses in the list pointed to by
174       res.   If  both AI_V4MAPPED and AI_ALL are specified in hints.ai_flags,
175       then return both IPv6  and  IPv4-mapped  IPv6  addresses  in  the  list
176       pointed to by res.  AI_ALL is ignored if AI_V4MAPPED is not also speci‐
177       fied.
178
179       The freeaddrinfo() function frees the memory that was allocated for the
180       dynamically allocated linked list res.
181
182   Extensions to getaddrinfo() for Internationalized Domain Names
183       Starting  with  glibc  2.3.4, getaddrinfo() has been extended to selec‐
184       tively allow the incoming and outgoing hostnames  to  be  transparently
185       converted  to  and  from the Internationalized Domain Name (IDN) format
186       (see RFC 3490, Internationalizing Domain Names in Applications (IDNA)).
187       Four new flags are defined:
188
189       AI_IDN If  this  flag is specified, then the node name given in node is
190              converted to IDN format if necessary.  The  source  encoding  is
191              that of the current locale.
192
193              If  the  input  name contains non-ASCII characters, then the IDN
194              encoding is used.  Those parts of the node  name  (delimited  by
195              dots)  that contain non-ASCII characters are encoded using ASCII
196              Compatible Encoding (ACE) before being passed to the name  reso‐
197              lution functions.
198
199       AI_CANONIDN
200              After a successful name lookup, and if the AI_CANONNAME flag was
201              specified, getaddrinfo() will return the canonical name  of  the
202              node  corresponding to the addrinfo structure value passed back.
203              The return value is an exact copy of the value returned  by  the
204              name resolution function.
205
206              If  the name is encoded using ACE, then it will contain the xn--
207              prefix for one or more components of the name.  To convert these
208              components  into  a  readable  form  the AI_CANONIDN flag can be
209              passed in addition to AI_CANONNAME.  The resulting string is en‐
210              coded using the current locale's encoding.
211
212       AI_IDN_ALLOW_UNASSIGNED, AI_IDN_USE_STD3_ASCII_RULES
213              Setting these flags will enable the IDNA_ALLOW_UNASSIGNED (allow
214              unassigned Unicode code  points)  and  IDNA_USE_STD3_ASCII_RULES
215              (check  output  to  make  sure it is a STD3 conforming hostname)
216              flags respectively to be used in the IDNA handling.
217

RETURN VALUE

219       getaddrinfo() returns 0 if it succeeds, or one of the following nonzero
220       error codes:
221
222       EAI_ADDRFAMILY
223              The  specified  network host does not have any network addresses
224              in the requested address family.
225
226       EAI_AGAIN
227              The name server returned a temporary  failure  indication.   Try
228              again later.
229
230       EAI_BADFLAGS
231              hints.ai_flags  contains  invalid  flags; or, hints.ai_flags in‐
232              cluded AI_CANONNAME and name was NULL.
233
234       EAI_FAIL
235              The name server returned a permanent failure indication.
236
237       EAI_FAMILY
238              The requested address family is not supported.
239
240       EAI_MEMORY
241              Out of memory.
242
243       EAI_NODATA
244              The specified network host exists, but does not have any network
245              addresses defined.
246
247       EAI_NONAME
248              The  node  or service is not known; or both node and service are
249              NULL; or AI_NUMERICSERV was specified in hints.ai_flags and ser‐
250              vice was not a numeric port-number string.
251
252       EAI_SERVICE
253              The  requested service is not available for the requested socket
254              type.  It may be available through another socket type.  For ex‐
255              ample,  this error could occur if service was "shell" (a service
256              available only on stream sockets), and either  hints.ai_protocol
257              was IPPROTO_UDP, or hints.ai_socktype was SOCK_DGRAM; or the er‐
258              ror could occur if service was not NULL,  and  hints.ai_socktype
259              was SOCK_RAW (a socket type that does not support the concept of
260              services).
261
262       EAI_SOCKTYPE
263              The requested socket type is not supported.  This  could  occur,
264              for  example, if hints.ai_socktype and hints.ai_protocol are in‐
265              consistent (e.g., SOCK_DGRAM and IPPROTO_TCP, respectively).
266
267       EAI_SYSTEM
268              Other system error; errno is set to indicate the error.
269
270       The gai_strerror() function translates these error  codes  to  a  human
271       readable string, suitable for error reporting.
272

FILES

274       /etc/gai.conf
275

ATTRIBUTES

277       For  an  explanation  of  the  terms  used  in  this  section,  see at‐
278       tributes(7).
279
280       ┌─────────────────────────────────┬───────────────┬────────────────────┐
281Interface                        Attribute     Value              
282       ├─────────────────────────────────┼───────────────┼────────────────────┤
283getaddrinfo()                    │ Thread safety │ MT-Safe env locale │
284       ├─────────────────────────────────┼───────────────┼────────────────────┤
285freeaddrinfo(), gai_strerror()   │ Thread safety │ MT-Safe            │
286       └─────────────────────────────────┴───────────────┴────────────────────┘
287

CONFORMING TO

289       POSIX.1-2001, POSIX.1-2008.  The getaddrinfo() function  is  documented
290       in RFC 2553.
291

NOTES

293       getaddrinfo() supports the address%scope-id notation for specifying the
294       IPv6 scope-ID.
295
296       AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3.
297       AI_NUMERICSERV is available since glibc 2.3.4.
298
299       According to POSIX.1, specifying hints as NULL should cause ai_flags to
300       be assumed as 0.   The  GNU  C  library  instead  assumes  a  value  of
301       (AI_V4MAPPED | AI_ADDRCONFIG)  for  this case, since this value is con‐
302       sidered an improvement on the specification.
303

EXAMPLES

305       The following programs demonstrate the use of  getaddrinfo(),  gai_str‐
306       error(),  freeaddrinfo(), and getnameinfo(3).  The programs are an echo
307       server and client for UDP datagrams.
308
309   Server program
310
311       #include <sys/types.h>
312       #include <stdio.h>
313       #include <stdlib.h>
314       #include <unistd.h>
315       #include <string.h>
316       #include <sys/socket.h>
317       #include <netdb.h>
318
319       #define BUF_SIZE 500
320
321       int
322       main(int argc, char *argv[])
323       {
324           struct addrinfo hints;
325           struct addrinfo *result, *rp;
326           int sfd, s;
327           struct sockaddr_storage peer_addr;
328           socklen_t peer_addr_len;
329           ssize_t nread;
330           char buf[BUF_SIZE];
331
332           if (argc != 2) {
333               fprintf(stderr, "Usage: %s port\n", argv[0]);
334               exit(EXIT_FAILURE);
335           }
336
337           memset(&hints, 0, sizeof(hints));
338           hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
339           hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
340           hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
341           hints.ai_protocol = 0;          /* Any protocol */
342           hints.ai_canonname = NULL;
343           hints.ai_addr = NULL;
344           hints.ai_next = NULL;
345
346           s = getaddrinfo(NULL, argv[1], &hints, &result);
347           if (s != 0) {
348               fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
349               exit(EXIT_FAILURE);
350           }
351
352           /* getaddrinfo() returns a list of address structures.
353              Try each address until we successfully bind(2).
354              If socket(2) (or bind(2)) fails, we (close the socket
355              and) try the next address. */
356
357           for (rp = result; rp != NULL; rp = rp->ai_next) {
358               sfd = socket(rp->ai_family, rp->ai_socktype,
359                       rp->ai_protocol);
360               if (sfd == -1)
361                   continue;
362
363               if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
364                   break;                  /* Success */
365
366               close(sfd);
367           }
368
369           freeaddrinfo(result);           /* No longer needed */
370
371           if (rp == NULL) {               /* No address succeeded */
372               fprintf(stderr, "Could not bind\n");
373               exit(EXIT_FAILURE);
374           }
375
376           /* Read datagrams and echo them back to sender. */
377
378           for (;;) {
379               peer_addr_len = sizeof(peer_addr);
380               nread = recvfrom(sfd, buf, BUF_SIZE, 0,
381                       (struct sockaddr *) &peer_addr, &peer_addr_len);
382               if (nread == -1)
383                   continue;               /* Ignore failed request */
384
385               char host[NI_MAXHOST], service[NI_MAXSERV];
386
387               s = getnameinfo((struct sockaddr *) &peer_addr,
388                               peer_addr_len, host, NI_MAXHOST,
389                               service, NI_MAXSERV, NI_NUMERICSERV);
390               if (s == 0)
391                   printf("Received %zd bytes from %s:%s\n",
392                           nread, host, service);
393               else
394                   fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
395
396               if (sendto(sfd, buf, nread, 0,
397                           (struct sockaddr *) &peer_addr,
398                           peer_addr_len) != nread)
399                   fprintf(stderr, "Error sending response\n");
400           }
401       }
402
403   Client program
404
405       #include <sys/types.h>
406       #include <sys/socket.h>
407       #include <netdb.h>
408       #include <stdio.h>
409       #include <stdlib.h>
410       #include <unistd.h>
411       #include <string.h>
412
413       #define BUF_SIZE 500
414
415       int
416       main(int argc, char *argv[])
417       {
418           struct addrinfo hints;
419           struct addrinfo *result, *rp;
420           int sfd, s;
421           size_t len;
422           ssize_t nread;
423           char buf[BUF_SIZE];
424
425           if (argc < 3) {
426               fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
427               exit(EXIT_FAILURE);
428           }
429
430           /* Obtain address(es) matching host/port. */
431
432           memset(&hints, 0, sizeof(hints));
433           hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
434           hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
435           hints.ai_flags = 0;
436           hints.ai_protocol = 0;          /* Any protocol */
437
438           s = getaddrinfo(argv[1], argv[2], &hints, &result);
439           if (s != 0) {
440               fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
441               exit(EXIT_FAILURE);
442           }
443
444           /* getaddrinfo() returns a list of address structures.
445              Try each address until we successfully connect(2).
446              If socket(2) (or connect(2)) fails, we (close the socket
447              and) try the next address. */
448
449           for (rp = result; rp != NULL; rp = rp->ai_next) {
450               sfd = socket(rp->ai_family, rp->ai_socktype,
451                            rp->ai_protocol);
452               if (sfd == -1)
453                   continue;
454
455               if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
456                   break;                  /* Success */
457
458               close(sfd);
459           }
460
461           freeaddrinfo(result);           /* No longer needed */
462
463           if (rp == NULL) {               /* No address succeeded */
464               fprintf(stderr, "Could not connect\n");
465               exit(EXIT_FAILURE);
466           }
467
468           /* Send remaining command-line arguments as separate
469              datagrams, and read responses from server. */
470
471           for (int j = 3; j < argc; j++) {
472               len = strlen(argv[j]) + 1;
473                       /* +1 for terminating null byte */
474
475               if (len > BUF_SIZE) {
476                   fprintf(stderr,
477                           "Ignoring long message in argument %d\n", j);
478                   continue;
479               }
480
481               if (write(sfd, argv[j], len) != len) {
482                   fprintf(stderr, "partial/failed write\n");
483                   exit(EXIT_FAILURE);
484               }
485
486               nread = read(sfd, buf, BUF_SIZE);
487               if (nread == -1) {
488                   perror("read");
489                   exit(EXIT_FAILURE);
490               }
491
492               printf("Received %zd bytes: %s\n", nread, buf);
493           }
494
495           exit(EXIT_SUCCESS);
496       }
497

SEE ALSO

499       getaddrinfo_a(3),    gethostbyname(3),     getnameinfo(3),     inet(3),
500       gai.conf(5), hostname(7), ip(7)
501

COLOPHON

503       This  page  is  part of release 5.13 of the Linux man-pages project.  A
504       description of the project, information about reporting bugs,  and  the
505       latest     version     of     this    page,    can    be    found    at
506       https://www.kernel.org/doc/man-pages/.
507
508
509
510GNU                               2021-08-27                    GETADDRINFO(3)
Impressum