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 *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           Since glibc 2.22: _POSIX_C_SOURCE >= 200112L
26           Glibc 2.21 and earlier: _POSIX_C_SOURCE
27

DESCRIPTION

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

RETURN VALUE

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

FILES

271       /etc/gai.conf
272

ATTRIBUTES

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

CONFORMING TO

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

NOTES

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

EXAMPLES

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

SEE ALSO

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

COLOPHON

501       This page is part of release 5.10 of the Linux  man-pages  project.   A
502       description  of  the project, information about reporting bugs, and the
503       latest    version    of    this    page,    can     be     found     at
504       https://www.kernel.org/doc/man-pages/.
505
506
507
508GNU                               2020-11-01                    GETADDRINFO(3)
Impressum