简体   繁体   English

提取DNS A记录的TTL值

[英]Extracting TTL value of a DNS A record

I am doing some dns stuff and I require to do an A record lookup for an SRV and extract ttl and ip address from it: 我正在做一些dns的工作,我需要对SRV进行A记录查找,并从中提取ttl和ip地址:

I was able to extract ip using the following code, but how do I extract TTL? 我可以使用以下代码提取ip,但是如何提取TTL?

 l = res_query(argv[1], ns_c_any, ns_t_a, nsbuf, sizeof(nsbuf));
    if (l < 0)
    {
      perror(argv[1]);
    }
    ns_initparse(nsbuf, l, &msg);
    l = ns_msg_count(msg, ns_s_an);
    for (i = 0; i < l; i++)
    {
      ns_parserr(&msg, ns_s_an, 0, &rr);
      ns_sprintrr(&msg, &rr, NULL, NULL, dispbuf, sizeof(dispbuf));
      printf("\t%s \n", dispbuf);
      inet_ntop(AF_INET, ns_rr_rdata(rr), debuf, sizeof(debuf));
      printf("\t%s \n", debuf);
    }

Output: 输出:

./a.out sip-anycast-1.voice.google.com
        sip-anycast-1.voice.google.com.  21h55m46s IN A  216.239.32.1
        216.239.32.1

Following mostly your code, you can retrieve the IP and TTL in this way (I fixed up your ns_parserr() call so that it iterates through multiple entries in the response properly): 大部分遵循您的代码,您可以通过这种方式检索IP和TTL(我修复了ns_parserr()调用,以便它可以正确地遍历响应中的多个条目):

    l = res_query(argv[1], ns_c_any, ns_t_a, nsbuf, sizeof(nsbuf));
    if (l < 0) {
        perror(argv[1]);
        exit(EXIT_FAILURE);
    }
    ns_initparse(nsbuf, l, &msg);
    c = ns_msg_count(msg, ns_s_an);
    for (i = 0; i < c; ++i) {
        ns_parserr(&msg, ns_s_an, i, &rr);
        ns_sprintrr(&msg, &rr, NULL, NULL, dispbuf, sizeof(dispbuf));
        printf("%s\n", dispbuf);
        if (ns_rr_type(rr) == ns_t_a) {
            uint8_t ip[4];
            uint32_t ttl = ns_rr_ttl(rr);
            memcpy(ip, ns_rr_rdata(rr), sizeof(ip));
            printf("ip: %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
            printf("ttl: %u\n", ttl);
        }
    }

It produces the following output: 它产生以下输出:

$ ./a.out myserver.mydomain.com
myserver.mydomain.com.  1H IN A         172.16.1.21
ip: 172.16.1.21
ttl: 3600

I was not able to find very much documentation on the libresolv library, and it seems that the shared library libresolv.so does not include all the symbols needed to link the program. 我在libresolv库上找不到太多的文档,而且共享库libresolv.so似乎没有包含链接程序所需的所有符号。 So, I had to compile the program like this: 因此,我必须像这样编译程序:

$ gcc test_resolv.c -static -lresolv -dynamic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM