如何计算具有IP-in-bit表示的下一个IP地址



我从DHCP信息中获取IP地址。当我有IP位表示时,如何计算下一个IP地址。

WifiManager wifii = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo d = wifii.getDhcpInfo();
int mask = d.netmask;
int ip0 = d.ipAddress & d.netmask;
int num = ~d.netmask; //it should be correct but don't work. why?
//this don't work. How make it correct?
for(int ip = ip0; ip < ip + num; ip++){
   //here ip next ip
}

IP=192.168.1.16和网络掩码255.255.255.0的示例:

int ipAddress = 0xC0A80110;
int mask = 0xFFFFFF00;
int maskedIp = ipAddress & mask;
int ip = ipAddress;
// Loop until we have left the unmasked region
while ((mask & ip) == maskedIp) {
    printIP(ip);
    ip++;
}

根据Robert的建议,一个简单的解决方案是从您的ip上下测试它们:

int ip = d.ipAddress;
while (ip & d.netmask) {
    // Valid ip
    ip++
}
ip = d.ipAddress - 1;
while (ip & d.netmask) {
    // Valid ip
    ip--
}

最新更新