Beej\'s Simple Client example code iterates over all IP addresses returned from getaddrinfo(), until it can connect to the first one. See the code below.
Is this always
Yes, you should iterate over all the addresses - in particular, consider the case when the destination host has IPv6 addresses enabled but your local host does not. getaddrinfo()
will return AF_INET6
family addresses, but then either the socket()
or connect()
call will fail.
It's also a possibility that your host supports multiple protocols implementing SOCK_STREAM
(say, SCTP in addition to TCP) and the destination host does not - since you haven't set the ai_protocol
member of the hints structure, addresses representing all protocols supporting SOCK_STREAM
sockets will be returned.