【问题标题】:How calculate next IP adress having ip in bit representation?如何计算以位表示的具有 ip 的下一个 IP 地址?
【发布时间】:2012-08-30 06:20:36
【问题描述】:

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

【问题讨论】:

  • 字节顺序没有正确记录。也许这不是您所期望的(小端与大端)。你有没有看过你实际得到的值?他们可能会提供线索...
  • 我知道掩码 00000000.11111111.11111111.11111111 是 255.255.255.0
  • 十个问题,没有接受的答案?我想说你很幸运能得到这个问题的答案。如果您将来想要好的答案,您应该真正接受答案(当然,如果它们可以接受的话)。请检查您的旧问题并“接受”您使用的答案。
  • @njzk2 其实我也不知道为什么还要把ip地址倒过来。这篇文章“stackoverflow.com/questions/5387036/…”告诉我intToIp(int i) 可以工作,但我发现返回字符串仍然存在字节序问题。不知道这是为什么?

标签: java android ip netmask


【解决方案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++;
}

【讨论】:

    【解决方案2】:

    根据 Robert 的建议,一个简单的解决方案是测试您的 ips 并对其进行测试:

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

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多