前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >简单解析DNS

简单解析DNS

原创
作者头像
8菠萝
发布2023-08-24 16:18:12
1950
发布2023-08-24 16:18:12
举报
文章被收录于专栏:菠萝上市没有
代码语言:txt
复制
#include <stdio.h>
#include <netdb.h>
#include <ares.h>
#include <arpa/inet.h>
#include <string.h>


int main(int argc, char* argv[])
{
    if (argc <= 1){
        return 0;
    }

    ares_channel channel;
    int status;
    status = ares_library_init(ARES_LIB_INIT_ALL);
    if (status != ARES_SUCCESS){
        puts("Error");
        return 0;
    }
    status = ares_init(&channel);
    if (status != ARES_SUCCESS){
        puts("Error2");
        return 0;
    }

    ares_set_servers_csv(channel, "8.8.8.8");
    ares_gethostbyname(channel, argv[1], AF_INET, [](auto arg, auto status, auto timeouts, auto hosten)->void {
        if (status == ARES_SUCCESS){
            struct in_addr  addr;
            memcpy(&addr, hosten->h_addr_list[0], hosten->h_length);
            printf("IP Address: %s\n", inet_ntoa(addr));
        }
        else{
            printf("DNS resolution failed.\n");
        }
    }, nullptr);

    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    fd_set read_fds, write_fds;
    int nfds = ares_fds(channel, &read_fds, &write_fds);
    while (nfds > 0){
        select(nfds, &read_fds, &write_fds, nullptr, &tv);
        ares_process(channel, &read_fds, &write_fds);
        nfds = ares_fds(channel, &read_fds, &write_fds);
    }
    ares_destroy(channel);
    ares_library_cleanup();
    return 0;
}

命令:

g++-8 reslove_dns.cpp -o dns_query -lcares结果:

./dns_query qq.com

IP Address: 183.3.226.35

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档