Littlegator
Littlegator

Reputation: 395

Will getaddrinfo() on the host ever return more than one IPv4 address?

Say I call getaddrinfo() as below:

addrinfo hints;
addrinfo* res = NULL;

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

getaddrinfo(NULL, "http", &hints, &res);

Is it currently possible for the results of this to contain more than one result with an IPv4 address? The only reason I could think of is possibly multiple devices with separate connections, but I'm half expecting it to only return the address of the primary connection or the one connection it happens to use.

Upvotes: 2

Views: 3228

Answers (2)

Rick
Rick

Reputation: 7516

I had this confusion too and I did some research.

Quoted from The Linux Programming Interface

int getaddrinfo(const char * host , const char * service ,
const struct addrinfo * hints , struct addrinfo ** result );

The result argument returns a list of structures, rather than a single structure, because there may be multiple combinations of host and service corresponding to the criteria specified in host, service, and hints. For example, multiple address structures could be returned for a host with more than one network interface.

I tested with my own domain copyqwer.com

DNS setting:

Type    Name        Value               TTL 
A       @           23.106.150.74       600 seconds 
A       @           111.222.17.173      600 seconds

and getaddrinfo returns addr structures with these 2 different ip address.

A full example. https://onlinegdb.com/ry1cdoAKr

Output on my computer (I don't know why there's no UDP ouput on my local computer, but that doesn't matter)

/home/*****/CLionProjects/APUE/cmake-build-debug/APUE copyqwer.com http
flags canon family inet type stream protocol TCP
    host copyqwer.com address 111.222.17.173 port 80
flags canon family inet type stream protocol TCP
    host - address 23.106.150.74 port 80

Upvotes: 1

fork0
fork0

Reputation: 3459

Yes.

The man page on getaddrinfo has following to say on the topic

There are several reasons why the linked list may have more than one addrinfo structure, including: the network host is multihomed, accessible over multiple protocols (e.g. both AF_INET and AF_INET6); or the same service is available from multiple socket types (one SOCK_STREAM address and another SOCK_DGRAM address, for example). Normally, the application should try using the addresses in the order in which they are returned. The sorting function used within getaddrinfo() is defined in RFC 3484; the order can be tweaked for a particular system by editing /etc/gai.conf (available since glibc 2.5).

Upvotes: 6

Related Questions