hostsaddrinfo() is called from hosts() for non-IP keys, e.g.
`getent hosts foo openbsd.org'.
Using getnameinfo(2) simplifies the code, makes it less address family
specific and plays nicely with previously used getaddrinfo(2).
While here, make function paramter `const', sort stack variables by size
nit-pick PF_UNSPEC.
No observable change in behaviour/output.
OK?
Index: getent.c
===================================================================
RCS file: /cvs/src/usr.bin/getent/getent.c,v
retrieving revision 1.14
diff -u -p -r1.14 getent.c
--- getent.c 1 Feb 2016 19:57:28 -0000 1.14
+++ getent.c 24 Sep 2018 23:00:14 -0000
@@ -227,42 +227,30 @@ hostsprint(const struct hostent *he)
printfmtstrings(he->h_aliases, " ", " ", "%-16s %s", buf, he->h_name);
}
static int
-hostsaddrinfo(char* name)
+hostsaddrinfo(const char *name)
{
struct addrinfo hints, *res, *res0;
- void *src;
- int rv;
char buf[INET6_ADDRSTRLEN];
+ int rv;
rv = RV_NOTFOUND;
memset(buf, 0, sizeof(buf));
memset(&hints, 0, sizeof(hints));
- hints.ai_family = PF_UNSPEC;
+ hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
- if (getaddrinfo(name, NULL, &hints, &res0) == 0) {
- for (res = res0; res; res = res->ai_next) {
- switch (res->ai_family) {
- case AF_INET:
- src = &((struct sockaddr_in*)
- res->ai_addr)->sin_addr;
- break;
- case AF_INET6:
- src = &((struct sockaddr_in6*)
- res->ai_addr)->sin6_addr;
- break;
- default: /* not reached */
- src = NULL;
- }
- if (src==NULL || inet_ntop(res->ai_family, src, buf,
- sizeof(buf)) == NULL)
- strlcpy(buf, "# unknown", sizeof(buf));
- else
- rv = RV_OK;
- printf("%-39s %s\n", buf, name);
- }
- freeaddrinfo(res0);
+ if (getaddrinfo(name, NULL, &hints, &res0) != 0)
+ return (rv);
+ for (res = res0; res; res = res->ai_next) {
+ if ((res->ai_family != AF_INET6 && res->ai_family != AF_INET) ||
+ getnameinfo(res->ai_addr, res->ai_addrlen, buf, sizeof(buf),
+ NULL, 0, NI_NUMERICHOST) != 0)
+ strlcpy(buf, "# unknown", sizeof(buf));
+ else
+ rv = RV_OK;
+ printf("%-39s %s\n", buf, name);
}
+ freeaddrinfo(res0);
return (rv);
}