title: How do I read the subnet mask from getifaddr
body: <p>Using <code>getifaddrs()</code> function I'm wanting to extract the network ip and mask
  in CIDR format (i.e. 24 instead of 255.255.255.0) which is different than other questions.  But I'm having difficulty with the mask part. </p>
  
  <p>For example:</p>
  
  <p>192.168.0.114/24</p>
  
  <p>This is what I have be messing around with so far.  But I must be reading the netmask incorrectly.  It's completely wrong.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;ifaddrs.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;string.h&gt;
  #include &lt;arpa/inet.h&gt;
  
  unsigned int cidrMask(unsigned int n) {
      unsigned int count = 0;
      while (n) {
          count += n &amp; 1;
          n &gt;&gt;= 1;
      }
      return 32-count;
  }
  
  
  int main (int argc, const char * argv[]) {
      struct ifaddrs * ifAddrStruct=NULL;
      struct ifaddrs * ifa=NULL;
      void * tmpAddrPtr=NULL;
      unsigned int tmpMask;
  
      getifaddrs(&amp;ifAddrStruct);
  
      for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa-&gt;ifa_next) {
          if (!ifa-&gt;ifa_addr) {
              continue;
          }
  
          if (ifa-&gt;ifa_addr-&gt;sa_family == AF_INET) { // check it is IP4
              // is a valid IP4 Address
              tmpAddrPtr=&amp;((struct sockaddr_in *)ifa-&gt;ifa_addr)-&gt;sin_addr;
              memcpy(&amp;tmpMask, &amp;(*(struct sockaddr_in *)&amp;ifa-&gt;ifa_netmask).sin_addr, 4);
  
              char addressBuffer[INET_ADDRSTRLEN];
              inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
              printf("%s IP Address %s, mask=%u, %u\n", ifa-&gt;ifa_name, addressBuffer, ifa-&gt;ifa_netmask, cidrMask(tmpMask));
                  printf("tmpmask=%d\n", tmpMask);
          }
      }
      if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
      return 0;
  }
  </code></pre>
  
  <p>So the output for the netmask is completely wrong.</p>
  
  <pre><code>lo IP Address 127.0.0.1, mask=3106544572, 22
  tmpmask=21982
  enp0s25 IP Address 192.168.0.114, mask=3106544756, 22
  tmpmask=21982
  docker0 IP Address 172.17.0.1, mask=3106544940, 22
  tmpmask=21982
  </code></pre>
  
  <p>How do I read the netmask and produce correct output?</p>