title: Is there a way to get the IP address from the interface name, in Linux, without relying on ioctl or getifaddrs?
body: <p>I need to get the IP address of a certain Linux interface, programmatically and using C, given its name.</p>
  
  <p>I know that I can do this by relying on <code>ioctl</code>, like in the following code snippet:</p>
  
  <pre><code>struct ifreq ifreq;
  struct in_addr ifIP;
  int dummysfd;
  
  dummysfd=socket(AF_INET,SOCK_DGRAM,0);
  
  // devname is a char* containing my interface name
  strncpy(ifreq.ifr_name,devname,IFNAMSIZ);
  ifreq.ifr_addr.sa_family=AF_INET;
  if(ioctl(dummysfd,SIOCGIFADDR,&amp;ifreq)!=-1) {
      ifIP=((struct sockaddr_in*)&amp;ifreq.ifr_addr)-&gt;sin_addr;
  } else {
      fprintf(stderr,"Error: cannot retrieve IP address for interface %s.\n",devname);
  }
  
  close(dummysfd);
  </code></pre>
  
  <p>This solution, even though it works correctly, has the drawback of requiring the creation of a dummy socket, just to get the IP address.</p>
  
  <p>My doubt is whether another method exists to get the IP address directly from the interface name without, for instance, scanning all the available interfaces (as it would be when using <code>getifaddrs</code>) and without relying on a method which requires opening a dummy socket to be passed to <code>ioctl</code>.</p>
  
  <p>Does a function like <code>if_nametoindex()</code> (defined in <code>&lt;net/if.h&gt;</code>) exist, but which returns the IP address instead of the index?</p>