[英]The purpose of ai_next and ai_addr inside the addrinfo struct
I am teaching myself socket programming and I've recently come across getaddrinfo
and the addrinfo
struct. 我正在自学套接字编程,我最近遇到了
getaddrinfo
和addrinfo
结构。 From my understanding, the majority of the files in the struct are ints that you can use by specifying macros, for example, if I wanted to AF_INET
in my addrinfo
struct, I would specify either AF_INET
, or the integer 2 (I don't know this for sure, what header file is it declared in?). 从我的理解,多数在结构中的文件,你可以通过指定的宏,例如,如果我想使用整数
AF_INET
在我addrinfo
结构,我想请指定AF_INET
,或整数2(我不知道这一点,它声明了什么头文件?)。 Well, I don't think I quite understand why there is an sockaddr and pointer to another addrinfo. 好吧,我不认为我完全理解为什么有一个sockaddr和指向另一个addrinfo的指针。 I've been told that the latter creates a linked list, but what is the purpose behind it?
我被告知后者会创建一个链表,但它背后的目的是什么?
I would recommend always specifying the values using the type names. 我建议始终使用类型名称指定值。 They may be different on different systems.
它们在不同系统上可能不同。
The getaddrinfo(3) man page describes the fields of the addrinfo
struct, but to summarize the way the linked list works, consider this code: getaddrinfo(3)手册页描述了
addrinfo
结构的字段,但是为了总结链表的工作方式,请考虑以下代码:
for (struct addrinfo *ai = ...; ai != NULL; ai = ai->ai_next) {
printf("address: %s -> %s\n", ai->ai_canonname,
inet_ntop(ai->ai_family, ai->ai_addr, buf, buflen));
}
The addrinfo*
you get back from getaddrinfo
may point to another one, which may point to another, and so on. 你从
getaddrinfo
回来的addrinfo*
可能指向另一个,可能指向另一个,依此类推。 This is how it represents an address which can resolve to multiple different IPs (for load balancing, dual-stack IPv4/IPv6, etc). 这就是它如何表示可以解析为多个不同IP的地址(用于负载平衡,双栈IPv4 / IPv6等)。
Okay, the main question is - "what is the reason behind it?". 好的,主要的问题是 - “它背后的原因是什么?”。 The reason is, one host could've multiple internet address assigned to it.
原因是,一个主机可以分配多个互联网地址。 For ex, if you run "host www.google.com" command this will give you multiple internet address, so the point of linked list of multiple addrinfo is to keep all the returned internet addresses, thus allowing you to properly translate network address and service.
例如,如果您运行“主机www.google.com”命令,这将为您提供多个互联网地址,因此多个addrinfo链接列表的重点是保留所有返回的互联网地址,从而允许您正确翻译网络地址和服务。
When you write an app and trying to connect to a public server that might have multiple internet address, these linked list of address will give you the flexibility of making a connection to an appropriate interface. 当您编写应用程序并尝试连接到可能具有多个Internet地址的公共服务器时,这些链接的地址列表将使您可以灵活地连接到适当的接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.