Since you have several addrinfo structures organized in a linked list, you should addrinfo over it and try connect until the connection is successful. I.e:
struct addrinfo *ptr = res; while (res != NULL) { int rc = connect(socket_fd, (sockaddr *) ptr->ai_addr, ptr->addr_len); if (rc == 0) break;
This may be required because a DNS lookup can return multiple records, so you need to have a linked list so that you can access them. If connect succeeds, you are done; if it fails, you should continue to try for each available IP address to return, so move the pointer to the next item. Also, consider that connect may fail for several reasons, so you need to check errno for errors that further attempts may allow. As @R .. noted, you also need to pass a new socket to connect , as the address family may change, releasing the previous one; getaddrinfo will help you, as this information is provided in addrinfo node ( ai_family ).
However, this is usually not necessary: ββthe first result, as a rule, will work. Personally, if I can, I have never encountered the need to iterate over a linked list, but it's still good to know if you might need it.
getaddrinfo (3)
There are several reasons why a linked list can have more than one addrinfo structure, including: a network host is multi-network, accessible via several protocols (for example, both AF_INET and AF_INET6); or the same service is available from several types of sockets (for example, one SOCK_STREAM address and another SOCK_DGRAM address). Typically, an application should try to use the addresses in the order in which they are returned. The sort function used in getaddrinfo () is defined in RFC 3484; the order can be changed for a specific system by editing /etc/gai.conf (available with glibc 2.5).
source share