Is it necessary to attempt to connect to all addresses returned by getaddrinfo()?

后端 未结 5 2235
甜味超标
甜味超标 2021-02-14 16:33

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

相关标签:
5条回答
  • 2021-02-14 16:56

    Assuming you are new to socket, at this point. Yes, it is crucial because after using getaddrinfo, you can retrieve a address info for further validation.

    0 讨论(0)
  • 2021-02-14 17:01

    Let look at tit this way... The server host you want to connect to may have several addresses associated with it, but the actual server program only listens on one of those addresses. If your client doesn't know the exact address the server program is listening to, you have to try all the addresses the host has until you find the correct one and can connect.

    0 讨论(0)
  • 2021-02-14 17:01

    Yes, you should loop through all of them -- there's no guarantee that the first one (or whatever you pick) of the addresses will actually be valid. That's why it's done like that in the tutorial.

    0 讨论(0)
  • 2021-02-14 17:02

    In addition to the other answers given above, consider the common case that for larger websites and so on, that multiple A records might be published, for redundancy purposes. If a connect() to the first address fails, you want to try the others as well.

    0 讨论(0)
  • 2021-02-14 17:08

    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.

    0 讨论(0)
提交回复
热议问题