【问题标题】:How to get the maximum number of hosts from IP address如何从IP地址获取最大主机数
【发布时间】:2019-02-13 09:55:39
【问题描述】:

我的问题是如何获取指定IP地址所属网络可以使用的最大主机数。

我有一个像这样的 java 方法,它有两个参数 ip 地址和子网掩码地址。 当我用谷歌搜索时,我找到了公式,但我不知道如何用 java 编写。 公式是

最大主机数可以根据主机数来确定 在网络中可用,是减去两个得到的数字 少和广播地址。

public static int maxHostNum(String _ip, String _subnetMask) throws UnknownHostException {
    byte[] bIP = InetAddress.getByName(_ip).getAddress();
    byte[] bSB = InetAddress.getByName(_subnetMask).getAddress();
    byte[] bNT = new byte[4];
    for (int i=0; i<bIP.length; i++) {
        bNT[i] = (byte) (~bSB[i] | bIP[i]);
    }
    String broadcastAddress = InetAddress.getByAddress(bNT).toString();

    // i dont know the rest

    return maxHostNum;
}

我知道 Apache 通用库可以做到这一点,但我只想不使用库来做到这一点

【问题讨论】:

  • 例如,如果 ip 地址 = 192.168.2。 65,子网掩码地址=255.255.255.192,那么最大主机数=62
  • 你真的需要IP吗?我认为只有子网掩码就足够了。

标签: java binary byte ip-address


【解决方案1】:

子网掩码通过在掩码和 IP 之间执行按位与来获得网络 IP,来确定 IP 地址的哪一部分是网络 IP,哪一部分是设备的 IP。例如:

192.168.3.45 ->    11000000.10101000.00000011.00101101
255.255.255.240 -> 11111111.11111111.11111111.11110000
Network IP ->      11000000.10101000.00000011.00100000 <- because the last 4 digits of the subnet mask were 0 here, the resulting network IP bits are also 0.
Host IP ->         00000000.00000000.00000000.00001101

因此,由于在上面的示例中,最后 4 位数字确定主机 IP,因此您应该有 2^4 个可用 IP 地址,但实际上您有 2^4 - 2,因为所有主机位都是 1 或0 是特殊的,不能用于特定设备。

所以要知道一个网络可以支持多少主机 IP,您可以简单地反转子网掩码的值并将其转换为 int:

int result = 0;
for (int i = 0; i < bSB.length; i++) {
    result <<= 8; // Bit shift 8 digits to the left.
    result |= ~bSB[i]; // Perform bitwise or-equals with the bitwise inverted value of bSB[i]
}
result <<= 8;
result -= 2; // Special IPs

得到的整数是可能的主机 IP 数。

【讨论】:

    【解决方案2】:

    如果您可以转换为 cidr 表示法,那将很容易得到 2 个公式:

    Nbr 子网 = 2^(cidr-class)。 Nbr 个主机 = 2^(32-cidr) -2。

    如果是 A 类,则 class=8; 16 如果是 B 类; 24 如果是 C 类。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 2018-08-26
      • 2013-08-17
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多