blob: 49e4e53197d195d83a91ee4605c0cea7e5c8e9fa [file] [log] [blame]
Rich Felker0b44a032011-02-12 00:22:29 -05001#define _GNU_SOURCE
2
3#include <sys/socket.h>
4#include <netdb.h>
5#include <string.h>
6#include <netinet/in.h>
7#include <errno.h>
8#include <inttypes.h>
9
10int gethostbyname2_r(const char *name, int af,
11 struct hostent *h, char *buf, size_t buflen,
12 struct hostent **res, int *err)
13{
14 struct addrinfo hint = {
15 .ai_family = af==AF_INET6 ? af : AF_INET,
16 .ai_flags = AI_CANONNAME
17 };
18 struct addrinfo *ai, *p;
19 int i;
20 size_t need;
21 const char *canon;
22
23 af = hint.ai_family;
24
25 /* Align buffer */
26 i = (uintptr_t)buf & sizeof(char *)-1;
27 if (i) {
Rich Felker70b584b2013-02-02 01:31:10 -050028 if (buflen < sizeof(char *)-i) return ERANGE;
Rich Felker0b44a032011-02-12 00:22:29 -050029 buf += sizeof(char *)-i;
30 buflen -= sizeof(char *)-i;
31 }
32
33 getaddrinfo(name, 0, &hint, &ai);
34 switch (getaddrinfo(name, 0, &hint, &ai)) {
35 case EAI_NONAME:
36 *err = HOST_NOT_FOUND;
Rich Felker70b584b2013-02-02 01:31:10 -050037 return errno;
Rich Felker0b44a032011-02-12 00:22:29 -050038 case EAI_AGAIN:
39 *err = TRY_AGAIN;
Rich Felker70b584b2013-02-02 01:31:10 -050040 return errno;
Rich Felker0b44a032011-02-12 00:22:29 -050041 default:
42 case EAI_MEMORY:
43 case EAI_SYSTEM:
44 case EAI_FAIL:
45 *err = NO_RECOVERY;
Rich Felker70b584b2013-02-02 01:31:10 -050046 return errno;
Rich Felker0b44a032011-02-12 00:22:29 -050047 case 0:
48 break;
49 }
50
51 h->h_addrtype = af;
52 h->h_length = af==AF_INET6 ? 16 : 4;
53
54 canon = ai->ai_canonname ? ai->ai_canonname : name;
55 need = 4*sizeof(char *);
56 for (i=0, p=ai; p; i++, p=p->ai_next)
57 need += sizeof(char *) + h->h_length;
58 need += strlen(name)+1;
59 need += strlen(canon)+1;
60
61 if (need > buflen) {
62 freeaddrinfo(ai);
Rich Felker70b584b2013-02-02 01:31:10 -050063 return ERANGE;
Rich Felker0b44a032011-02-12 00:22:29 -050064 }
65
66 h->h_aliases = (void *)buf;
67 buf += 3*sizeof(char *);
68 h->h_addr_list = (void *)buf;
69 buf += (i+1)*sizeof(char *);
70
71 h->h_name = h->h_aliases[0] = buf;
72 strcpy(h->h_name, canon);
73 buf += strlen(h->h_name)+1;
74
75 if (strcmp(h->h_name, name)) {
76 h->h_aliases[1] = buf;
77 strcpy(h->h_aliases[1], name);
78 buf += strlen(h->h_aliases[1])+1;
79 } else h->h_aliases[1] = 0;
80
81 h->h_aliases[2] = 0;
82
83 for (i=0, p=ai; p; i++, p=p->ai_next) {
84 h->h_addr_list[i] = (void *)buf;
85 buf += h->h_length;
86 memcpy(h->h_addr_list[i],
87 &((struct sockaddr_in *)p->ai_addr)->sin_addr,
88 h->h_length);
89 }
90 h->h_addr_list[i] = 0;
91
92 *res = h;
93 freeaddrinfo(ai);
94 return 0;
95}