c-ares DNS域名异步解析成IP

该博客介绍了如何在C++中利用c-ares库进行DNS异步解析。通过ares_init初始化通道,设置DNS服务器为114.114.114.114,然后使用ares_gethostbyname获取主机名对应的IP地址。ares_callback函数处理解析结果,将IP地址转换为字符串并存储。在主函数中,不断循环解析输入的主机名并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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;
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值