子網掩碼、掩碼長度關系


/*****************************************************************************
 *                          子網掩碼、掩碼長度關系
 * 聲明:
 *     我們在操作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);
            }
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM