Skip to content

Instantly share code, notes, and snippets.

@Morozov-5F
Created August 30, 2017 15:15
Show Gist options
  • Save Morozov-5F/31aeeae4b21b4575b76561286e860efd to your computer and use it in GitHub Desktop.
Save Morozov-5F/31aeeae4b21b4575b76561286e860efd to your computer and use it in GitHub Desktop.
DNS resolve using c-ares
#include <ares.h>
#include <stdio.h>
#include <netdb.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#define HOST_TO_RESOLVE "yandex.ru"
#define GOOGLE_DNS_SERVER 0x08080808
#define DNS_WATCH_SERVER 0x54C84550
static void ares_lookup_completed(void * arg, int status, int timeouts, struct hostent * hostent)
{
if (status != ARES_SUCCESS)
{
printf("Unable to resolve host %s\n", HOST_TO_RESOLVE);
goto done;
}
printf("Resolved host: %u.%u.%u.%u for %s\n", (unsigned char)hostent->h_addr[0],
(unsigned char)hostent->h_addr[1],
(unsigned char)hostent->h_addr[2],
(unsigned char)hostent->h_addr[3],
hostent->h_name);
done:
return;
}
int main()
{
ares_channel channel;
int nfds, count;
fd_set readers, writers;
struct timeval tv, *tvp;
struct in_addr dns_servers[] = {
{ .s_addr = GOOGLE_DNS_SERVER },
{ .s_addr = DNS_WATCH_SERVER },
};
struct ares_options options = {
.servers = dns_servers,
.nservers = 2
};
printf("Initializing c-ares...");
assert(ARES_SUCCESS == ares_init_options(&channel, &options, ARES_OPT_SERVERS));
printf("\tOK\n");
printf("Trying to resolve host %s...\n", HOST_TO_RESOLVE);
ares_gethostbyname(channel, HOST_TO_RESOLVE, AF_INET, ares_lookup_completed, NULL);
while (1)
{
FD_ZERO(&readers);
FD_ZERO(&writers);
nfds = ares_fds(channel, &readers, &writers);
if (nfds == 0)
{
break;
}
tvp = ares_timeout(channel, NULL, &tv);
count = select(nfds, &readers, &writers, NULL, tvp);
ares_process(channel, &readers, &writers);
sleep(1);
}
printf("Destroying c-ares...");
ares_destroy(channel);
printf("\tOK\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment