以编程方式检索 IPv4 和 IPv6 名称服务器 [英] Retrieve IPv4 and IPv6 nameservers programmatically
问题描述
我正在尝试使用 libresolv 读取 /etc/resolv.conf
文件中的 IPv4 和 IPv6 名称服务器:
I'm trying to use libresolv to read both the IPv4 and IPv6 nameservers in my /etc/resolv.conf
file:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.
nameserver 127.0.0.53
nameserver 2001:4860:4860:0:0:0:0:8888
这是我的 C 程序:
#include <resolv.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
res_state res = malloc(sizeof(struct __res_state));
res_ninit(res);
printf("IPv4 nscount: %d
", res->nscount);
printf("IPv6 nscount6: %d
", res->_u._ext.nscount6);
return 0;
}
产生这个输出:
IPv4 nscount: 2
IPv6 nscount6: 0
这让我很惊讶.为什么将 IPv6 地址算作 IPv4 地址?
Which surprises me. Why is it counting the IPv6 address as an IPv4 address?
GDB 显示第二个地址被清零:
GDB shows that the second address is zeroed out:
(gdb) display res.nsaddr_list[0]
5: res.nsaddr_list[0] = {sin_family = 2, sin_port = 13568, sin_addr = {s_addr = 889192575}, sin_zero = " 00 00 00 00 00 00 00"}
(gdb) display res.nsaddr_list[1]
6: res.nsaddr_list[1] = {sin_family = 0, sin_port = 0, sin_addr = {s_addr = 0}, sin_zero = " 00 00 00 00 00 00 00"}
谁能帮我理解这种行为?
Can anyone help me understand this behavior?
推荐答案
你真的不应该访问解析器状态的 _u._ext
部分,它们是一个内部实现细节.nscount6
成员当前未使用且始终为零.必须保留它以避免由于结构偏移/大小更改而更改 ABI.
You really should not access the _u._ext
parts of the resolver state, they are an internal implementation detail. The nscount6
member is currently unused and always zero. It had to be kept to avoid changing the ABI as the result of struct offset/size changes.
如果你需要域名服务器列表,你应该自己解析/etc/resolv.conf
.请注意,最终 glibc 也将支持三个以上的名称服务器,这些额外的解析器不会反映在公共解析器状态中.
If you need the nameserver list, you should parse /etc/resolv.conf
yourself. Note that eventually, glibc will also support more than three name servers, and those extra resolvers will not be reflected in the public resolver state.
这篇关于以编程方式检索 IPv4 和 IPv6 名称服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!