本文主要是介绍使用c-ares进行DNS域名解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、c-ares是一个C语言实现的DNS非阻塞异步解析,libcurl, libevent, gevent, nodejs wireshark都使用了c-ares,因此在一般开发一些服务的客户端Client,在连接服务器Server时,需要做的工作的就是域名解析。
2、源码下载路径: https://c-ares.haxx.se/download/
3、编译使用
(1)Win32环境
源码下载解压后,进入vs文件夹,使用VS2013等工具打开工程,即可以编译Win32的caresd.lib和caresd.dll
static int CloudServerHostIsIP(const char * serverhost)
{struct in_addr addr;int lsuccess;lsuccess= inet_pton(AF_INET, serverhost, &addr);return lsuccess> 0 ? 0 : -1;
}static void DNSCallBack(void* arg, int status, int timeouts, struct hostent* host)
{char **lpSrc;char * lpHost = (char *)arg;if (status == ARES_SUCCESS){for (lpSrc = host->h_addr_list; *lpSrc; lpSrc++){char addr_buf[32] = "";ares_inet_ntop(host->h_addrtype, *lpSrc, addr_buf, sizeof(addr_buf));if (strlen(addr_buf) != 0){strcpy(lpHost, addr_buf);break;}}}
}static int DomainNameReSolution(const char * lpDomainName, char * lpHost)
{int lsuccess= 0;ares_channel channel;lsuccess= ares_library_init(ARES_LIB_INIT_ALL);if ((lsuccess= ares_init(&channel)) != ARES_SUCCESS) return -1;int trytime = 3;do{fd_set readers, writers;timeval tv;tv.tv_sec = 5;tv.tv_usec = 0;FD_ZERO(&readers);FD_ZERO(&writers);ares_gethostbyname(channel, lpDomainName, AF_INET, DNSCallBack, (char *)lpHost);int nfds = ares_fds(channel, &readers, &writers);if (nfds == 0){continue;}int count = select(nfds, &readers, NULL, NULL, &tv);if (count > 0){ares_process(channel, &readers, &writers);lsuccess= 0;break;}else{lsuccess= -1;}} while (trytime-- > 0);ares_destroy(channel);ares_library_cleanup();return lsuccess;
}
这篇关于使用c-ares进行DNS域名解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!