0

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
}
LunaVulpo
  • 3,043
  • 5
  • 30
  • 58
  • The byte order is not properly documented. Maybe it is not what you expect (litte endian vs big endian). Have you taken a look at the values you actually get? They might give a clue... – user1252434 Sep 05 '12 at 14:02
  • I know that mask 00000000.11111111.11111111.11111111 is 255.255.255.0 – LunaVulpo Sep 05 '12 at 14:13
  • 1
    Ten questions and no accepted answers? I would say you have been lucky to get an answer at all to this question. If you want good answers in the future you should really accept answers (if they are acceptable of course). Please go over your old questions and "accept" the answers you used. – Some programmer dude Sep 05 '12 at 14:21
  • @njzk2 Actually I don't know why should I still have to reverse the ip address. This article 'http://stackoverflow.com/questions/5387036/programmatically-getting-the-gateway-and-subnet-mask-details' tells me that the `intToIp(int i)` would work, but I found that return string still have a endian issue. No idea why is that? – Alston Jul 25 '14 at 03:17

2 Answers2

1

Example for IP=192.168.1.16 and netmask 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
  • 39,162
  • 17
  • 99
  • 152
0

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--
}
njzk2
  • 38,969
  • 7
  • 69
  • 107