测试有效的方法,如果按位的IPv6网络掩码是连续 [英] Efficient way to test if bitwise IPv6 netmask is contiguous

查看:583
本文介绍了测试有效的方法,如果按位的IPv6网络掩码是连续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要IP地址/网络掩码存储在一个in_addr结构/ in6_addr结构。
对于IPv4我用下面的code,以测试网络掩码是连续的:

I need to store IP addresses/netmasks in an in_addr/in6_addr struct. For IPv4 I use the following code to test if the netmask is contiguous:

((((~netmask + 1) & (~netmask)) != 0)  && (netmask != 0))

我想知道是否有做同样的对IPv6的一个聪明的办法。

I was wondering if there is a smart way to do the same for IPv6.

推荐答案

一些编译器有128位整数。我在code,其使用上的AMD64架构的GCC编译使用__uint128_t。

Some compilers have 128 bit integers. I have used __uint128_t in code which was compiled using gcc on an AMD64 architecture.

如果您使用的是带有128位整数的编译器,你可以简单地重用现有code,因为它使这个字大小没有假设。

If you are using a compiler with 128 bit integers, you can simply reuse your existing code, since it makes no assumptions about the word size.

如果你需要一个较小的字大小进行计算,它自然就变得比较复杂,但数量不多。第一贯穿掩模的话的指针找到具有零位(例如)的第一个字:

If you need to perform the calculation with a smaller word size, it naturally gets more complicated, but not much. First run a pointer through the words of the mask to find the first word with a zero bit (for example):

for (i = 0; i < 4 && netmask[i] != 0xffffffff; ++i)

接下来,您可以将您的原始测试适用于网​​络掩码[I] ,最后你需要测试所有余下的字均为零。

Next you can apply your original test to netmask[i], finally you need to test that any remaining words are zero.

另一种方法是将原始测试适用于每个单词而且测试,每一个字对已首次为全1或第二为全零:

A different approach is to apply your original test to each individual word and moreover test that every pair of words has the first be all ones or the second be all zeros:

int contiguous(uint32_t **netmask)
{
    int i;
    for (i = 0; i < 4; ++i) {
        if ((~netmask[i] + 1) & (~netmask[i])) return 0;
    }
    for (i = 0; i < 3; ++i) {
        if ((netmask[i] != 0xffffffff) && (netmask[i+1] != 0)) return 0;
    }
    return 1;
}

您还可以采取更常见的做法,而不是采取面具作为输入,而是通过128作为输入,而不是采取指定为一个整数preFIX长度范围为0。然后你可以自己构建掩码,并知道它是连续的。

You can also take the more common approach and not take a mask as input but instead take a prefix length specified as an integer in the range 0 through 128 as the input. Then you can construct the bitmask yourself and know that it is contiguous.

这篇关于测试有效的方法,如果按位的IPv6网络掩码是连续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆