This is what I've done so far. It compiles, but it segfaults when I try to run it.
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <ares.h>
void dns_callback (void* arg, int status, int timeouts, struct hostent* host)
{
std::cout << host->h_name << "\n";
}
int main(int argc, char **argv)
{
struct in_addr ip;
char *arg;
inet_aton(argv[1], &ip);
ares_channel channel;
ares_gethostbyaddr(channel, &ip, 4, AF_INET, dns_callback, arg);
sleep(15);
return 0;
}
You atleast have to initialize the ares_channel before you use it
You also need an event loop to process events on the ares file descriptors and call ares_process to handle those events (more commonly, you'd integrate this in the event loop of your application) There's nothing magic with ares, it doesn't use threads to do the async processing so simply calling sleep(15); doesn't let ares run in the "background"
Your callback should also inspect the
status
variable, you can't accesshost->h_name
if the lookup failed.A full example becomes: