clinuxsocketsunix

Reverse name lookup with getnameinfo() doesn't work with custom sockaddr_in6


I wrote the following code and expect it to return the address of google.com. However, it returns me an empty string at the end. What do I need to fix to make it work? getnameinfo() gives me the error code of -6

#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <iostream>

int main(int argc, char* argv[]) {  
  const char* presentation_addr = "2001:4860:4860::8888";
  
  // create a socket structure 
  struct in6_addr in6;
  int retval = inet_pton(AF_INET6, presentation_addr, &in6);
  sockaddr_in6 in6_sa;
  in6_sa.sin6_addr = in6;
  in6_sa.sin6_family = AF_INET6;

  sockaddr *sa = (struct sockaddr* )&in6_sa;
  char buf[NI_MAXHOST];
  
  retval = getnameinfo(sa, sizeof(sa), buf, sizeof(buf), NULL, 0, NI_NAMEREQD);
  if (retval) {
    std::cout << "getnameinfo() errored with code " << retval << std::endl;
  }
  std::cout << buf << std::endl;
  return 0;
}


Solution

  • I rewrote the part with getnameinfo as this and it worked:

    retval = getnameinfo((struct sockaddr*)&in6_sa, sizeof(in6_sa), buf, sizeof(buf), NULL, 0, NI_NAMEREQD);