【发布时间】: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