C++中的静态 DNS 解析器

Static DNS resolver in C++

本文关键字:DNS 静态 C++      更新时间:2023-10-16

我正在尝试使用静态库在 c++ 中构建一个快速的 DNS 解析器(在任何地方都可以工作)。到目前为止,我的版本使用gethostbyname,在某些服务器上它不起作用,我得到A non-recoverable name server error occurred (NO_RECOVERY).同样在编译时,我们收到此警告:

Using 'gethostbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

#include <stdio.h>
#include <cstring>
// for dom
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    char* host = "google.com";
    int debugLevel = 5;
    char* ip_of_domain;
    struct hostent *he;
    he = gethostbyname(host);
    if (he == NULL)
    {
        switch(h_errno)
        {
            case HOST_NOT_FOUND:
                if(debugLevel >= 3) puts("The host was not found.");
                break;
            case NO_ADDRESS:
                if(debugLevel >= 3) puts("The name is valid but it has no address.");
                break;
            case NO_RECOVERY:
                if(debugLevel >= 3) puts("A non-recoverable name server error occurred.");
                break;
            case TRY_AGAIN:
                if(debugLevel >= 3) puts("The name server is temporarily unavailable.");
                break;
        }
    }
    else
    {
        ip_of_domain = strdup(inet_ntoa(*((struct in_addr *) he->h_addr_list[0])));
    }
    if(debugLevel >= 4) printf("IP=%sn",ip_of_domain);
}

该程序必须在 32 位和 64 位的每个位置兼容。

有什么解决办法吗?

谢谢。

使用 c-ares 库,这里:https://c-ares.haxx.se/。这是一个真正的独立于操作系统的解析器。