Should I try to connect to all the addresses returned by getaddrinfo ()?

The Beej Simple Client sample code is repeated for all IP addresses returned from getaddrinfo () until it can connect to the first. See code below.

Is this always necessary, or is it normal to assume that we only need to try connecting to the first address returned by getaddrinfo ()?

memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // ------------------------------------------------------------ // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } 
+8
c sockets network-programming getaddrinfo
source share
5 answers

Yes, you should iterate over all the addresses - in particular, consider the case where the recipient host has IPv6 addresses, but your local host does not. getaddrinfo() will return AF_INET6 family addresses, but then it will crash when calling socket() or connect() .

It is also possible that your host supports several protocols that implement SOCK_STREAM (let's say SCTP in addition to TCP), and the destination host does not, because you did not set the ai_protocol member in the hint structure, addresses representing all protocols that support SOCK_STREAM sockets.

+9
source share

In addition to the other answers above, consider the common case, which is for larger websites, etc. multiple A records may be published for redundancy purposes. If a connect() to the first address fails, you also want to try others.

+4
source share

Let's see how to do this ... The host of the server you want to connect to can have several addresses associated with it, but the actual server program listens for only one of these addresses. If your client does not know the exact address that the server program listens for, you should try all the addresses that the host has, until you find the correct one and can not connect.

+2
source share

Yes, you have to go through all of them - there is no guarantee that the first (or any other) that you have chosen will be valid. That is why it was done in a textbook.

+1
source share

Assuming you're new to the socket, at this point. Yes, this is important, because after using getaddrinfo you can get the address information for further verification.

0
source share

All Articles