问题描述
我为getaddrinfo编写了一个非常简单的测试程序:
I wrote a very simple test program for getaddrinfo:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main() {
struct addrinfo hints;
struct addrinfo *res, *rp;
char hoststr[64], servstr[8];
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "9998", &hints, &res);
for (rp = res; rp != NULL; rp = rp->ai_next) {
getnameinfo(rp->ai_addr, rp->ai_addrlen, hoststr, sizeof(hoststr),
servstr, sizeof(servstr), NI_NUMERICHOST | NI_NUMERICSERV);
printf("%s:%s\n", hoststr, servstr);
}
}
当我编译并运行该程序时,它会在IPv6地址之前给出IPv4地址:
When I compile and run this program, it's giving the IPv4 address before the IPv6 address:
# gcc -o getaddrinfo getaddrinfo.c
# ./getaddrinfo
0.0.0.0:9998
:::9998
据我从其他消息来源得知,IPv6地址应该比IPv4更可取.我正在使用默认的/etc/gai.conf,这意味着IPv6应该比IPv4更受青睐.那么为什么getaddrinfo会以这种方式排序?
As far as I can tell from other sources, IPv6 addresses are supposed to be preferred over IPv4. I'm using the default /etc/gai.conf which implies that IPv6 should be preferred over IPv4. So why is getaddrinfo sorting this way?
# ip addr show lo
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
推荐答案
从手册页开始:
您描述的行为是针对使用getaddrinfo()
查找名称以准备建立传出连接的行为.因为您要进行相反的操作,所以查找本地地址以绑定服务,因此显示地址的顺序无关紧要.
The behavior you're describing is for when you use getaddrinfo()
to look up a name in preparation to make an outgoing connection. Because you're doing the reverse, looking up a local address to bind for a service, the order the addresses are presented is irrelevant.
这篇关于getaddrinfo在本地主机的IPv6之前对IPv4进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!