Using getifaddrs()
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.
For example:
192.168.0.114/24
This is what I have be messing around with so far. But I must be reading the netmask incorrectly. It's completely wrong.
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
unsigned int cidrMask(unsigned int n) {
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 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(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
memcpy(&tmpMask, &(*(struct sockaddr_in *)&ifa->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->ifa_name, addressBuffer, ifa->ifa_netmask, cidrMask(tmpMask));
printf("tmpmask=%d\n", tmpMask);
}
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
return 0;
}
So the output for the netmask is completely wrong.
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
How do I read the netmask and produce correct output?