mardi 30 juillet 2019

How to find given IPv6 address falls in the CIDR range

If I have an ipv6 address 2001:4860:4860:0000:0000:0000:012D:8888 and want to find whether this falls in the given CIDR range 2001:4860:4860:0000:0000:0000:0000:8888/32. How do I do this in C or C++?

I tried similarly as we do for ipv4. (ip & netmask) == (range & netmask)

unsigned int ipv6 = (ip[0]<<112) + (ip[1]<<96) + (ip[2]<<80) + (ip[3]<<64)+ (ip[4]<<48) + (ip[5]<<32) + (ip[6]<<16) + ip[7];

unsigned int range = (cidr_ip[0]<<112) + (cidr_ip[1]<<96) + (cidr_ip[2]<<80) + (cidr_ip[3]<<64)+ (cidr_ip[4]<<48) + (cidr_ip[5]<<32) + (cidr_ip[6]<<16) + cidr_ip[7];
unsigned int mask = (~0u) << (128-netmask);

if((ipv6 & mask) == (range & mask)){
    printf("matched\n");
}
else
{
    printf("no match\n");
}


This didn't work for me as expected. The above ipv6 falls in the range. But the program says "no match".

Aucun commentaire:

Enregistrer un commentaire