Android获取当前子网掩码地址(亲测可用),现在网上好多都是通过DhcpInfo
来获取,但是通过这种方法有Bug,很多人用DhcpInfo
的方式都是获取不到,都是为0.0.0.0
。
以下为可用的方法
public static String getIpAddrMask() {
try {
Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
while (networkInterfaceEnumeration.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
if (!networkInterface.isUp()) {
continue;
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
if (interfaceAddress.getAddress() instanceof Inet4Address) {
return calcMaskByPrefixLength(interfaceAddress.getNetworkPrefixLength());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "get-error";
}
public static String calcMaskByPrefixLength(int length) {
int mask = 0xffffffff << (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;
}
I/System.out: 192.168.232.2
I/System.out: 255.255.248.0
I/System.out: 192.168.232.0/21