Search code examples
javaandroidipnetmask

How calculate next IP adress having ip in bit representation?


I get IP address form DHCP info. How calculate next IP address when I have IP in bit representation.

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
}

Solution

  • A simple solution, base on Robert's proposal, would be to test ips up and down from yours and test them :

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