0

I am studying this client example from man7, in the first for loop

           for (rp = result; rp != NULL; rp = rp->ai_next) {
               sfd = socket(rp->ai_family, rp->ai_socktype,
                            rp->ai_protocol);
               if (sfd == -1)
                   continue;

               if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
                   break;                  /* Success */

               close(sfd);
           }

also from man7

  struct addrinfo {
               int              ai_flags;
               int              ai_family;
               int              ai_socktype;
               int              ai_protocol;
               socklen_t        ai_addrlen;
               struct sockaddr *ai_addr;
               char            *ai_canonname;
               struct addrinfo *ai_next;
           };

this is how the struct addrinfo is defined, so when we use rp->ai_addr we get a pointer to another struct which is struct sockaddr that contains the ip address.

How do you access the value sa_data from struct sockaddr which is in rp->ai_addr, what functions are used for this purpose if any

The only thing I could figure out is adding printf("Connected %s\n", rp->ai_addr->sa_data); before break; but this does not print a valid ip address in my case it only prints a

  • `sa_data` is the address represented in a blob of binary. Use [`inet_ntop`](https://man7.org/linux/man-pages/man3/inet_ntop.3.html) to transform the address into a string. – user4581301 Jun 18 '22 at 20:03
  • @user4581301 can you show how to do that exactly in an answer please – packet_sniffer Jun 18 '22 at 20:08
  • [Use the `inet_ntop` portion of answer two of the first duplicate.](https://stackoverflow.com/a/29147085/4581301) – user4581301 Jun 18 '22 at 20:37
  • Alternatively, you can use [`getnameinfo()`](https://man7.org/linux/man-pages/man3/getnameinfo.3.html) with the `NI_NUMERICHOST` flag. That would be easier than using `inet_ntop()`, which requires you to manually interpret the `sockaddr` fields to break apart what is needed to pass to `inet_ntop()` – Remy Lebeau Jun 19 '22 at 07:55

0 Answers0