Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing DNS stub resolver (getaddrinfo(3))
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>
int main(int argc, char **argv)
{
struct addrinfo hints, *ai, *ai_p;
const char *name;
char addr[NI_MAXHOST];
int err;
if (argc != 2) {
printf("Usage: %s NAME\n", argv[0]);
return 1;
}
name = argv[1];
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
err = getaddrinfo(name, NULL, &hints, &ai);
if (err) {
fprintf(stderr, "%s: ERROR: %s\n", argv[0], gai_strerror(err));
return 1;
}
for (ai_p = ai; ai_p; ai_p = ai_p->ai_next){
void *ia;
switch (ai_p->ai_family) {
case AF_INET:
ia = &((struct sockaddr_in *)(ai_p->ai_addr))->sin_addr.s_addr;
break;
case AF_INET6:
ia = &((struct sockaddr_in6 *)(ai_p->ai_addr))->sin6_addr;
break;
default:
fprintf(stderr, "%s: ERROR: Unknown address family: %d\n", argv[0], ai_p->ai_family);
continue;
}
if (inet_ntop(ai_p->ai_family, ia, addr, sizeof(addr)) == NULL) {
fprintf(stderr, "%s: ERROR: inet_ntop() failed: %s\n", argv[0], strerror(errno));
continue;
}
printf("%s\n", addr);
}
freeaddrinfo(ai);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment