title: getnameinfo() from ifaddrs.h gives junk values in C
body: <p>I want to retrieve ip address of the current wireless interface I use. For that I use <code>getnameinfo()</code> function from <a href="http://man7.org/linux/man-pages/man3/getifaddrs.3.html" rel="nofollow noreferrer">ifaddrs.h</a> library. My problem is that this function return junk values rather than the actual ip address.</p>
  
  <p>Here is the function I use:</p>
  
  <pre><code>void getWIFromSystem(WI **WIHead) {
    struct ifaddrs *ifaddr, *ifa;
    char host[NI_MAXHOST];
  
    if (getifaddrs(&amp;ifaddr) == -1) {
      perror("getifaddrs");
      exit(-1);
    }
  
    /* Walk through linked list, maintaining head pointer so we
       can free list later */
    for (ifa = ifaddr; ifa != NULL; ifa = ifa-&gt;ifa_next) {
      if (ifa-&gt;ifa_addr == NULL || ifa-&gt;ifa_addr-&gt;sa_family != AF_PACKET) {
        continue;
      }
  
      if (check_wireless(ifa-&gt;ifa_name)) { / /we want only wireless interfaces
        //getWIAdress(ifa-&gt;ifa_name, host);
        getnameinfo(ifa-&gt;ifa_addr, (ifa-&gt;ifa_addr-&gt;sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
        addWI(&amp;WIHead, ifa-&gt;ifa_name, host);
      }
    }
  
    freeifaddrs(ifaddr);
  }
  </code></pre>
  
  <p>I manage to solve the problem with another function I created but I can't understand why I get junk values using the <code>getnameinfo()</code></p>
  
  <p>My other function that solves the problem:</p>
  
  <pre><code>void getWIAdress(char *name, char *host) {
     int fd;
     struct ifreq ifr;
  
     fd = socket(AF_INET, SOCK_DGRAM, 0);
  
     /* I want to get an IPv4 IP address */
     ifr.ifr_addr.sa_family = AF_INET;
  
     /* I want IP address attached to specified name */
     strncpy(ifr.ifr_name, name, IFNAMSIZ-1);
  
     ioctl(fd, SIOCGIFADDR, &amp;ifr);
  
     close(fd);
  
     /* copy result */
     strcpy(host, inet_ntoa(((struct sockaddr_in *)&amp;ifr.ifr_addr)-&gt;sin_addr));
  }
  </code></pre>
  
  <p>Screenshot of the junk values:</p>
  
  <p><a href="https://i.stack.imgur.com/JtivX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JtivX.png" alt="enter image description here"></a></p>