title: How can I prevent SIOCGIFADDR from failing?
body: <p>I want to get the eth0's IP. Here is what I've written (maybe there is a way around it?):</p>
  
  <pre><code>int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  check(sockfd &gt; 0, "cannot create socket\n");
  
  #define INTERFACE_NAME "eth0"
  #define INTERFACE_NAME_LENGTH 4
  
  char *opt = INTERFACE_NAME;
  rc = setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, opt, INTERFACE_NAME_LENGTH);
  check(rc == 0, "BINDTODEVICE failed");
  
  struct ifreq req;
  strncpy(req.ifr_name, INTERFACE_NAME, IFNAMSIZ);
  rc = ioctl(sockfd, SIOCGIFADDR, (unsigned long)&amp;req);
  check(rc == 0, "SIOCGIFADDR failed");
  server_ip = ((struct sockaddr_in*)&amp;req.ifr_addr)-&gt;sin_addr.s_addr;
  char str[50];
  inet_ntop(AF_INET, &amp;(server_ip), str, INET_ADDRSTRLEN);
  debug("serverip: %s", str);
  
  return sockfd;
  
  error:
  if (sockfd) close(sockfd);
  exit(1); 
  </code></pre>
  
  <p>I get the following error:</p>
  
  <blockquote>
    <p>[ERROR] (src/server/server.c:43: errno: Cannot assign requested address) SIOCGIFADDR failed</p>
  </blockquote>
  
  <p>If I use the same method with wlan0, I get what I'd expected to see. </p>
  
  <p>Here is the netstat output:</p>
  
  <p><strong>netstat -tulpn:</strong></p>
  
  <pre><code>Proto | Local Address   |  PID
  
  udp   | 0.0.0.0:16313   | 4666/dhclient   
  udp   | 0.0.0.0:68      | 4687/dhclient   
  udp   | 0.0.0.0:68      | 4666/dhclient 
  </code></pre>
  
  <p>So, I figure that I can't assign the address because of the dhclients? Why there are so many of them? and why there is one on the 16313 port? </p>
  
  <p>UPD:</p>
  
  <p>I added </p>
  
  <pre><code>auto eth0
  iface eth0 inet static
          address 192.168.1.1
          netmask 255.255.255.0
  </code></pre>
  
  <p>to /etc/network/interfaces and restarted the networking and got some progress: </p>
  
  <pre><code>DEBUG src/server/server.c:50: serverip: 192.168.1.1
  </code></pre>
  
  <p>and then I can successfully bind the socket, but the connection dies for no reason in a couple of seconds. </p>