【问题标题】:How do I resolve an IP into host using c-ares?如何使用 c-ares 将 IP 解析为主机?
【发布时间】:2011-06-18 18:20:56
【问题描述】:

这是我到目前为止所做的。它可以编译,但是当我尝试运行它时会出现段错误。

#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <ares.h>

void dns_callback (void* arg, int status, int timeouts, struct hostent* host)
  {
    std::cout << host->h_name << "\n";
  }

int main(int argc, char **argv)
  {
    struct in_addr ip;
    char *arg;
    inet_aton(argv[1], &ip);
    ares_channel channel;
    ares_gethostbyaddr(channel, &ip, 4, AF_INET, dns_callback, arg);
    sleep(15);
    return 0;
  }

【问题讨论】:

  • 为什么ares_gethostbyaddr()中的地址长度使用4而不是sizeof(in_addr)
  • 哦。我检查了一个使用这个库的程序,他们使用了 4,所以我认为它没问题。我将其更改为 sizeof(ip) 但它仍然存在段错误。
  • 另外,您的示例输入是什么?你能通过 gdb 运行它,看看它到底在哪里崩溃了吗?

标签: c++ linux dns c-ares


【解决方案1】:

您至少必须initialize ares_channel 才能使用它

 if(ares_init(&channel) != ARES_SUCCESS) {
   //handle error
  }

您还需要一个事件循环来处理 ares 文件描述符上的事件并调用 ares_process 来处理这些事件(更常见的是,您会将其集成到应用程序的事件循环中) ares 没有什么神奇之处,它不使用线程来进行异步处理,所以只需调用 sleep(15);不让战神在“后台”运行

您的回调还应检查status 变量,如果查找失败,您将无法访问host-&gt;h_name

一个完整的例子变成:

#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)
{
    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);
        if (nfds == 0)
          break;
        tvp = ares_timeout(channel, NULL, &tv);
        count = select(nfds, &readers, &writers, NULL, tvp);
        ares_process(channel, &readers, &writers);
     }

}
int main(int argc, char **argv)
{
    struct in_addr ip;
    int res;
    if(argc < 2 ) {
        std::cout << "usage: " << argv[0] << " ip.address\n";
        return 1;
    }
    inet_aton(argv[1], &ip);
    ares_channel channel;
    if((res = ares_init(&channel)) != ARES_SUCCESS) {
        std::cout << "ares feiled: " << res << '\n';
        return 1;
    }
    ares_gethostbyaddr(channel, &ip, sizeof ip, AF_INET, dns_callback, NULL);
    main_loop(channel);
    return 0;
  }
$ g++ -Wall test_ares.cpp -lcares $ ./a.out 8.8.8.8 google-public-dns-a.google.com

【讨论】:

  • 那是个错误。我没有调用 ares_init。该程序现在可以运行了。
  • 很久以前...但是我们不是必须先使用ares_library_init初始化库吗?
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2016-08-08
  • 2011-03-12
  • 2017-06-20
  • 1970-01-01
  • 2010-11-05
相关资源
最近更新 更多