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(): _POSIX_C_SOURCE >= 1 ||
25       _XOPEN_SOURCE || _POSIX_SOURCE
26

DESCRIPTION

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 multi-homed,  acces‐
129       sible  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 result only if the local system
156       has 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       result.  If both AI_V4MAPPED and AI_ALL are specified in  hints.ai_fam‐
163       ily,  then  return both IPv6 and IPv4-mapped IPv6 addresses in the list
164       pointed to by result.  AI_ALL is ignored if  AI_V4MAPPED  is  not  also
165       specified.
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

RETURN VALUE

207       getaddrinfo()  returns  0  if it succeeds, or one of the following non-
208       zero 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, repectively).
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

FILES

262       /etc/gai.conf
263

CONFORMING TO

265       POSIX.1-2001.  The getaddrinfo() function is documented in RFC 2553.
266

NOTES

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

EXAMPLE

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

SEE ALSO

469       gethostbyname(3), getnameinfo(3), inet(3), hostname(7), ip(7)
470

COLOPHON

472       This page is part of release 3.22 of the Linux  man-pages  project.   A
473       description  of  the project, and information about reporting bugs, can
474       be found at http://www.kernel.org/doc/man-pages/.
475
476
477
478GNU                               2008-12-04                    GETADDRINFO(3)
Impressum