How to print ip address from getaddrinfo

1.1k Views Asked by At

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

0

There are 0 best solutions below