How might I perform DNS lookups using C/C++ on Linux?

半城伤御伤魂 提交于 2019-12-18 05:45:08

问题


How do I get similar functionality to the host command using a c api (or any other language for that matter)? I need more information than just an IP address given by gethostbyname(); specifically, the SMTP-related data.


回答1:


If a blocking (synchronous) query is ok, just use res_query(), and link your program with -lresolv.

 len = res_query(host, C_IN, T_MX, &answer, sizeof(answer));



回答2:


I'd suggest FireDNS. It's a very fast C library for all kinds of dns queries.




回答3:


I know that the question is old, but I have long searched a dns library, and all answers here just stubs me. I think libraries like adns/udns have written not for human beings. And FireDNS for a long time have not working download links.

I have found poslib as the best dns library with very easy interface.




回答4:


I like adns because it allows for asynchronous requests




回答5:


And I would add, unless you're writing a mail relay you almost certainly shouldn't be looking up MX records - you should be passing the mail on to a user-configured mail relay instead.




回答6:


You can also try c-ares library https://c-ares.haxx.se/, which allows to send asynchronous DNS queries. It also comes with adig - its own version of dig utility for querying DNS. You can check it to see how to parse DNS reply: adig.c source




回答7:


I don't think there is a function in the C standard library for this, but many scripting languages do have this functionality 'built in'. For example, Perl has the Net::DNS package:

use Net::DNS;
my @mx = mx("example.com");
foreach $host (@mx) {
  print $host;
}

If you need to do this in C, a quick google shows up a few C libraries out there which you can use:

  • adns
  • udns
  • dns.c
  • FireDNS (as mentioned by ko-dos)


来源:https://stackoverflow.com/questions/1128409/how-might-i-perform-dns-lookups-using-c-c-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!