c-ares是一个C语言的异步DNS解析库,可以很方便的和使用者的事件循环统一起来,实现DNS的非
阻塞异步解析,libcurl, libevent, gevent, nodejs都在使用。
下面摘自Stack Overflow的一个例子,
#include <time.h>
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <ares.h>
void dns_callback (void* arg, int status, int timeouts, struct hostent* host) //ares 处理完成,返回DNS解析的信息
{
if(status == ARES_SUCCESS)
std::cout << host->h_name << "\n";
else
std::cout << "lookup failed: " << status << '\n';
}
void main_loop(ares_channel &channel)
{
int nfds, count;
fd_set readers, writers;
timeval tv, *tvp;
while (1) {
FD_ZERO(&readers);
FD_ZERO(&writers);
nfds = ares_fds(channel, &readers, &writers); //获取ares channel使用的FD
if (nfds == 0)
break;
tvp = a