//build1: g++ dns_parse_cares.cc /usr/local/lib/libcares.a -lrt -o test
//build2: g++ dns_parse_cares.cc -lcares -lrt -o test
#include <time.h>
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <ares.h>
#include <sys/select.h>
#include <string.h>
#define IP_LEN 32
typedef struct {
char host[64];
char ip[5][IP_LEN];
int count;
}IpList;
void dns_callback (void* arg, int status, int timeouts, struct hostent* hptr) //ares 处理完成,返回DNS解析的信息
{
IpList *ips = (IpList*)arg;
if( ips == NULL ) return;
if(status == ARES_SUCCESS){
strncpy(ips->host, hptr->h_name, sizeof(ips->host));
char **pptr=hptr->h_addr_list;
for(int i=0; *pptr!=NULL && i<5; pptr++,++i){
inet_ntop(hptr->h_addrtype, *pptr, ips->ip[ips->count++], IP_LEN);
}
}else{
std::cout << "lookup failed: " << status << std::endl;
c-ares DNS域名异步解析成IP
最新推荐文章于 2025-11-13 08:58:00 发布
该博客介绍了如何在C++中利用c-ares库进行DNS异步解析。通过ares_init初始化通道,设置DNS服务器为114.114.114.114,然后使用ares_gethostbyname获取主机名对应的IP地址。ares_callback函数处理解析结果,将IP地址转换为字符串并存储。在主函数中,不断循环解析输入的主机名并打印结果。

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



