首先,看看我的代码,我似乎应该拥有它,但较小的子网掩码似乎总是返回 true:
[root@hypervisor test]# ./test "99.99.99.99/8" 25.25.25.25
The given address is in the given cidr address
[root@hypervisor test]# ./test "99.99.99.99/16" 25.25.25.25
The given address is not in the given cidr address
[root@hypervisor test]# ./test "99.99.99.99/24" 25.25.25.25
The given address is not in the given cidr address
显然,最后两个检查是理想的。没有得到意想不到的负面结果,只是误报。仅当我指定低于 10 的子网掩码时,它似乎也会失败:
[root@hypervisor test]# ./test "99.99.99.99/9" 25.25.25.25
The given address is in the given cidr address
[root@hypervisor test]# ./test "99.99.99.99/10" 25.25.25.25
The given address is not in the given cidr address
[root@hypervisor test]#
这是我为完成这项工作而定义的函数(程序的其余部分本质上是返回代码上的 if/else,“给定 IP 在子网中”上的一个,“给定 IP 在子网外”上的零):
int inSubnet(const char *cidrNotation, const char *needleAddress){
char subnetDesignation[25], strPad[25];
unsigned short int maskSize;
unsigned int startOfCidr=strlen(cidrNotation)-3;
unsigned long int subnetMask=0, givenIP, subnetAddress;
unsigned short int iter=0;
/* BEGIN sanitization of arguments */
// If they gave real CIDR clip it off the end and save it.
if (strstr(cidrNotation, "/")){
strcpy(strPad, cidrNotation);
maskSize=atoi( (strPad+startOfCidr+1) );
*(strPad+startOfCidr) = '\0';
strcpy(subnetDesignation, strPad);
// Otherwise assume 32-bit mask (effectively equates two specific addys)
} else {
strcpy(subnetDesignation, cidrNotation);
maskSize=32;
} /* END SANITIZATION */
// Generate subnet mask in network byte order
for (iter=1; iter<maskSize; iter++){
subnetMask=subnetMask<<1; // move mask right by one, fill LSB with zero
subnetMask++; // flip the one bit on
}
// Get subnetDesignation into binary form and
inet_pton(AF_INET, subnetDesignation, &subnetAddress);
subnetAddress=subnetAddress & subnetMask; // Ensure it matches the subnet's prefix no matter how it was given
inet_pton(AF_INET, needleAddress, &givenIP);
// Since all non-subnet bits are flipped, the result of an AND should be identical to the subnet address.
if ( (givenIP & subnetAddress) == subnetAddress)
return 1;
else
return 0;
}
似乎我非常接近完成项目的这一部分,我只是做了某种疏忽,我只是以某种方式错过了。