如何在位表示中计算具有ip的下一个IP地址?

时间:2012-09-05 13:48:46

标签: java android ip netmask

我从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
}

2 个答案:

答案 0 :(得分:1)

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++;
}

答案 1 :(得分:0)

根据罗伯特的提议,一个简单的解决方案是从你的上下测试ips并测试它们:

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