子网掩码、掩码长度关系

/*****************************************************************************
 *                          子网掩码、掩码长度关系
 * 声明:
 *     我们在操作Linux系统的时候,经常看到可以使用子网掩码、掩码长度来表示掩码,
 * 对我来说,一直好奇的是子网掩码之间的1能不能夹一个0,如果夹了零,掩码长度就
 * 不好计算了,其中感谢johnason在讨论中给出的一些意见。
 *
 *                                           2016-5-5 深圳 南山平山村 曾剑锋
 ****************************************************************************/

一、参考文章:
    1. Netmask v. Address Prefix Length
        http://www.gadgetwiz.com/network/netmask.html
    2. android.net.NetworkUtils
        http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/net/NetworkUtils.java#NetworkUtils.netmaskIntToPrefixLength%28int%29

二、原因(参考文章解释):
    Netmasks are only counted as the number of zeros from the right; there are no zeros in the middle of a netmask. After all, a netmask like 255.255.255.250 (...11111010) wouldn't make much sense since it would refer to a range including only odd ip addresses. It wouldn't be a range at all! Consequently, there are only a few valid network masks. Each specify a number half the size of the prior netmask.

三、总结:
    从参考文章里可知,子网掩码的前面的1之间是不允许存在0的,当然,如果存在0,那么计算掩码长度的时候就无法计算了。

四、子网掩码、掩码长度转换:
    android.net.NetworkUtils
        1. Convert a IPv4 netmask integer to a prefix length
        2. Parameters:
            netmask as an integer in network byte order
        3. Returns:
            the network prefix length
        4. code:
            public static int More ...netmaskIntToPrefixLength(int netmask) {
                return Integer.bitCount(netmask);
            }
        
原文地址:https://www.cnblogs.com/zengjfgit/p/5461622.html