title: How to set the IP address from C in linux
body: <p>By using strace and ifconfig, I found that I can set the IP address this way:</p>
  
  <pre><code>#include &lt;sys/ioctl.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;net/if.h&gt;
  #include &lt;string.h&gt;
  
  int main(int argc, const char *argv[]) {
      struct ifreq ifr;
      const char * name = "eth1";
      int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  
      strncpy(ifr.ifr_name, name, IFNAMSIZ);
  
      ifr.ifr_addr.sa_family = AF_INET;
      inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);
      ioctl(fd, SIOCSIFADDR, &amp;ifr);
  
      inet_pton(AF_INET, "255.255.0.0", ifr.ifr_addr.sa_data + 2);
      ioctl(fd, SIOCSIFNETMASK, &amp;ifr);
  
      ioctl(fd, SIOCGIFFLAGS, &amp;ifr);
      strncpy(ifr.ifr_name, name, IFNAMSIZ);
      ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
  
      ioctl(fd, SIOCSIFFLAGS, &amp;ifr);
  
      return 0;
  }
  </code></pre>
  
  <p>But I am not very happy with this solution:</p>
  
  <pre><code>inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);
  </code></pre>
  
  <p>What is the "right" way of doing this?</p>