我需要从我的应用程序中解析一些主机名。有没有 gethostbyname 的替代方法,我可以在其中将我自己的 DNS 服务器作为参数作为解析器使用?
我已经编写了自己的函数,但我想可能还有一个我不知道的。
我正在使用 Linux/C 语言。我的 libc 是 uclibc。但我也对 GNU LibC 感到好奇。
谢谢。
最佳答案
您需要自己进行查询,但这并不困难。
为此,您需要使用 res_query()
函数族,允许您通过环境变量指定解析器:
The res_init() function reads the configuration files (see resolv.conf(5)) to get the default domain name, search order and name server address(es). If no server is given, the local host is tried. If no domain is given, that associated with the local host is used. It can be overridden with the environment variable LOCALDOMAIN
IBM 的 docs更深入地了解如何设置变量:
The configured search list (struct state.defdname and struct state.dnsrch) can be overridden by setting the environment variable LOCALDOMAIN to a space-separated list of up to 6 search domains with a total of 256 characters (including spaces). If a search list is specified, the default local domain is not used on queries.
注释-
您应该在调用
res_init()
之前调用setenv()
,否则设置将不会被选取。如果适用,记得在完成后取消设置如果您使用主机名作为搜索域,
/etc/hosts
仍然优先。res_init()
是 made properly reentrant in uclibc in 2007 ,所以我很确定您可以将它用于任何目的。
这些函数还有一个额外的好处,就是能够检索更详细的数据(MX 等)。尽管如此,如果您有更小但同样运行良好的东西,那么不使用它是没有意义的。
关于c - 替代 gethostbyname 我可以在哪里选择 DNS 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082557/