暗无天日

=============>DarkSun的个人博客

使用C语言获取DNS nameserver并进行域名解析

#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>

int main()
{
  res_init();
  int i = 0;
  for (i = 0;i< _res.nscount;i++) /* _res.nscount为找到的域名服务器的数量 */
    {
      struct sockaddr_in addr = _res.nsaddr_list[i]; /* 域名服务器的地址  */
    }
  int class = C_IN;
  int type = T_A;
  unsigned char answer[512]="";
  int n =res_query("www.baidu.com", class, type, answer, sizeof(answer)); /* answer中为域名解析的结果 */
  res_close();
  for(int i=0; i<n; i++){
    printf("%02x", answer[i]);
  }
}
4d20818000010003000000000377777705626169647503636f6d0000010001c00c0005000100000258000f0377777701610673686966656ec016c02b000100010000025800040ed7b126c02b000100010000025800040ed7b127

这种方法由于使用到了静态全局变量 _res,因此并不是线程安全的。为此glib提供了线程安全的对应函数 res_ninit, res_nquery, res_nclose:

#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>

int main()
{
  res_state res = malloc(sizeof(*res));
  res_ninit(res);
  int i = 0;
  for (i = 0;i< res->nscount;i++) /* res->nscount存储了域名服务器的个数 */
    {
      struct sockaddr_in addr = res->nsaddr_list[i]; /* 域名服务器的地址 */
    }
  int class = C_IN;
  int type = T_A;
  unsigned char answer[256]="";
  int n =res_nquery(res, "www.baidu.com", class, type, answer, sizeof(answer));  /* answer中为域名解析的结果 */
  res_nclose(res);
  for(int i=0; i<n; i++){
    printf("%02x", answer[i]);
  }
}
9965818000010003000000000377777705626169647503636f6d0000010001c00c0005000100000258000f0377777701610673686966656ec016c02b000100010000025800040ed7b127c02b000100010000025800040ed7b126

其中:

其他函数说明可以参见 man resolver.