简体   繁体   中英

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. 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?). Well, I don't think I quite understand why there is an sockaddr and pointer to another 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:

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. This is how it represents an address which can resolve to multiple different IPs (for load balancing, dual-stack IPv4/IPv6, etc).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM