如何使用c-ares将IP解析为主机名?

8

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

#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)作为地址长度? - chrisaycock
哦。我检查了一个使用这个库的程序,他们使用了4,所以我认为没问题。我把它改成了sizeof(ip),但仍然出现了段错误。 - greenman
另外,你的样本输入是什么?你能够通过gdb运行它以查看它在哪里崩溃吗? - chrisaycock
1个回答

14

在使用ares_channel之前,你至少需要初始化它。

 if(ares_init(&channel) != ARES_SUCCESS) {
   //handle error
  }
你还需要一个事件循环来处理ares文件描述符上的事件,并调用ares_process来处理这些事件(更常见的是在应用程序的事件循环中集成它)。
ares没有使用线程来进行异步处理,因此简单地调用sleep(15);不能让ares在“后台”运行。
如果查找失败,你的回调函数还应该检查status变量,否则你无法访问host->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。现在程序可以工作了。 - greenman
太久远了...但我们不是首先要使用ares_library_init初始化库吗? - duong_dajgja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接