我一直在关注Beej的网络编程指南,我很难理解为什么在调用getaddrinfo()之前我们必须填写struct addrinfo的一些字段?另外,为什么它返回一个指向多个 addrinfo结构列表的指针?由于只有一个主机,为什么有多个地址?
答案 0 :(得分:0)
为什么我们必须先填写struct addrinfo的一些字段 调用getaddrinfo()?
我假设你在询问hints
参数。此参数可用于指定要从getaddrinfo()
获取的响应类型。例如,您是否想要仅支持IPv4的DNS查询(AF_INET
)或IPv6(AF_INET6
)来自man page:
hints参数指向指定的addrinfo结构 选择返回的套接字地址结构的标准 res指出的列表。如果提示不是NULL,则指向a addrinfo结构,其ai_family,ai_socktype和ai_protocol 指定限制返回的套接字地址集的条件 getaddrinfo(),如下:
ai_family This field specifies the desired address family for the returned addresses. Valid values for this field include AF_INET and AF_INET6. The value AF_UNSPEC indicates that getaddrinfo() should return socket addresses for any address family (either IPv4 or IPv6, for example) that can be used with node and service. ai_socktype This field specifies the preferred socket type, for example SOCK_STREAM or SOCK_DGRAM. Specifying 0 in this field indicates that socket addresses of any type can be returned by getaddrinfo(). ai_protocol This field specifies the protocol for the returned socket addresses. Specifying 0 in this field indicates that socket addresses with any protocol can be returned by getaddrinfo(). ai_flags This field specifies additional options, described below. Multiple flags are specified by bitwise OR-ing them together. All the other fields in the structure pointed to by hints must contain either 0 or a null pointer, as appropriate.
为什么它返回一个指向多个addrinfo结构列表的指针? 由于只有一个主机,为什么有多个地址?
域名通常被解析为多个IP地址。
例如,对我来说,stackoverflow.com
目前已解析为以下地址:
$ nslookup stackoverflow.com
Non-authoritative answer:
Server: UnKnown
Address: 10.0.0.138
Name: stackoverflow.com
Addresses: 151.101.65.69
151.101.129.69
151.101.1.69
151.101.193.69
所有这些地址都是stackoverflow.com