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

RETURN VALUE

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

FILES

269       /etc/gai.conf
270

ATTRIBUTES

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

CONFORMING TO

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

NOTES

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

EXAMPLE

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

SEE ALSO

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

COLOPHON

499       This page is part of release 4.16 of the Linux  man-pages  project.   A
500       description  of  the project, information about reporting bugs, and the
501       latest    version    of    this    page,    can     be     found     at
502       https://www.kernel.org/doc/man-pages/.
503
504
505
506GNU                               2017-09-15                    GETADDRINFO(3)
Impressum