gethostbyaddr_r.c 1.5 KB
Newer Older
R
Rich Felker 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#define _GNU_SOURCE

#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <netinet/in.h>
#include <errno.h>
#include <inttypes.h>

int gethostbyaddr_r(const void *a, socklen_t l, int af,
	struct hostent *h, char *buf, size_t buflen,
	struct hostent **res, int *err)
{
	union {
		struct sockaddr_in sin;
		struct sockaddr_in6 sin6;
	} sa = { .sin.sin_family = af };
	socklen_t sl = af==AF_INET6 ? sizeof sa.sin6 : sizeof sa.sin;
	int i;

21 22
	*res = 0;

R
Rich Felker 已提交
23 24 25 26 27
	/* Load address argument into sockaddr structure */
	if (af==AF_INET6 && l==16) memcpy(&sa.sin6.sin6_addr, a, 16);
	else if (af==AF_INET && l==4) memcpy(&sa.sin.sin_addr, a, 4);
	else {
		*err = NO_RECOVERY;
28
		return EINVAL;
R
Rich Felker 已提交
29 30 31 32 33
	}

	/* Align buffer and check for space for pointers and ip address */
	i = (uintptr_t)buf & sizeof(char *)-1;
	if (!i) i = sizeof(char *);
34
	if (buflen <= 5*sizeof(char *)-i + l) return ERANGE;
R
Rich Felker 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	buf += sizeof(char *)-i;
	buflen -= 5*sizeof(char *)-i + l;

	h->h_addr_list = (void *)buf;
	buf += 2*sizeof(char *);
	h->h_aliases = (void *)buf;
	buf += 2*sizeof(char *);

	h->h_addr_list[0] = buf;
	memcpy(h->h_addr_list[0], a, l);
	buf += l;
	h->h_addr_list[1] = 0;
	h->h_aliases[0] = buf;
	h->h_aliases[1] = 0;

	switch (getnameinfo((void *)&sa, sl, buf, buflen, 0, 0, 0)) {
	case EAI_AGAIN:
		*err = TRY_AGAIN;
53
		return EAGAIN;
R
Rich Felker 已提交
54
	case EAI_OVERFLOW:
55
		return ERANGE;
R
Rich Felker 已提交
56 57 58 59 60
	default:
	case EAI_MEMORY:
	case EAI_SYSTEM:
	case EAI_FAIL:
		*err = NO_RECOVERY;
61
		return errno;
R
Rich Felker 已提交
62 63 64 65 66 67 68 69 70
	case 0:
		break;
	}

	h->h_addrtype = af;
	h->h_name = h->h_aliases[0];
	*res = h;
	return 0;
}