Search code examples
socketsunixgetaddrinfo

What to do with the results of getaddrinfo?


Using getaddrinfo to query a host, I get a number of results:

struct addrinfo hints;
hints.ai_flags    = 0
hints.ai_family   = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0
hints.ai_addrlen  = 0;
hints.ai_addr     = NULL;
hints.ai_canonname= NULL;
hints.ai_next     = NULL;

struct addrinfo *res = NULL;
getaddrinfo("google.com", "http", &hints, &res);

res gets filled in with a list of 11 possible addresses I could use to connect to google.com with the given parameters:

1   family=2, addr.port=80, addr.address=74.125.226.98, protocol=6, socktype=1, flags=0
2   family=2, addr.port=80, addr.address=74.125.226.104, protocol=6, socktype=1, flags=0
3   family=2, addr.port=80, addr.address=74.125.226.100, protocol=6, socktype=1, flags=0
4   family=2, addr.port=80, addr.address=74.125.226.99, protocol=6, socktype=1, flags=0
5   family=2, addr.port=80, addr.address=74.125.226.96, protocol=6, socktype=1, flags=0
6   family=2, addr.port=80, addr.address=74.125.226.102, protocol=6, socktype=1, flags=0
7   family=2, addr.port=80, addr.address=74.125.226.110, protocol=6, socktype=1, flags=0
8   family=2, addr.port=80, addr.address=74.125.226.97, protocol=6, socktype=1, flags=0
9   family=2, addr.port=80, addr.address=74.125.226.105, protocol=6, socktype=1, flags=0
10  family=2, addr.port=80, addr.address=74.125.226.103, protocol=6, socktype=1, flags=0
11  family=2, addr.port=80, addr.address=74.125.226.101, protocol=6, socktype=1, flags=0

My question is, which do I use? Should I just always take the first one, or pick one at random? Or should I try each one in order until connect() succeeds?


Solution

  • There is not an officially defined order, but unless you have a good reason not to: try them in order, skipping any that don't match your requirements (eg, wrong protocol). Usually DNS servers will round-robin or somehow permute the results. (You can probably see that if your run your test multiple times in a row or running nslookup or dig a few times on google.com.)

    https://en.wikipedia.org/wiki/Round-robin_DNS