AnsweredAssumed Answered

為何在android4.3上寫的netmask功能的code在android5.1.1上會有問題呢?

Question asked by chen sam on Aug 28, 2017

Hi,All:

我目前遇到一個大問題,我使用下列的code達成在android4.3上的LAN netmask功能,但為何這段code我搬移上android5.1.1就會有問題呢? 導致我抓的罩遮不正確呢?

這可能的原因是?

 

在拜託大大們,幫幫忙看看這是什麼原因造成的呢?

感謝大家了!!!

code如下:

public void SubnetMaskAddresses() {
    Enumeration<NetworkInterface> nwis;
    try {
        nwis = NetworkInterface.getNetworkInterfaces();
        while (nwis.hasMoreElements()) {

            NetworkInterface ni = nwis.nextElement();
           
            for (InterfaceAddress ia : ni.getInterfaceAddresses())
                SubnetMask = calcMaskByPrefixLength(ia.getNetworkPrefixLength());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

public static String calcMaskByPrefixLength(int length) {  
        int mask = -1 << (32 - length); 
        int partsNum = 4; 
        int bitsOfPart = 8; 
        int maskParts[] = new int[partsNum]; 
        int selector = 0x000000ff; 
 
        for (int i = 0; i < maskParts.length; i++) { 
            int pos = maskParts.length - 1 - i; 
            maskParts[pos] = (mask >> (i * bitsOfPart)) & selector; 
        } 
 
        String result = ""; 
        result = result + maskParts[0]; 
        for (int i = 1; i < maskParts.length; i++) { 
            result = result + "." + maskParts[i]; 
        } 
        return result; 
}   

Outcomes