1

首先,看看我的代码,我似乎应该拥有它,但较小的子网掩码似乎总是返回 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;

}

似乎我非常接近完成项目的这一部分,我只是做了某种疏忽,我只是以某种方式错过了。

4

1 回答 1

2

我认为您不能安全地假设网络掩码始终在字符串末尾占据三个字符:

unsigned int startOfCidr=strlen(cidrNotation)-3;

例如,当您有一个/8掩码时,您只需使用两个字符来指定它。(这可能也是它适用于 >= 10 的所有内容的原因。)尝试搜索一个/字符并从那里开始解析网络掩码。

于 2013-06-03T21:07:05.320 回答