如何根据子网掩码判断两个IP是否在同一网络?
例如,我有 IP 1.2.3.4 和 1.2.4.3:如果掩码为 255.0.0.0 或 255.255.0.0 甚至 255.255.248.0,则两者都在同一网络中,但如果掩码为 255.255.255.0 则不在同一个网络中。
最佳答案
试试这个方法:
public static boolean sameNetwork(String ip1, String ip2, String mask)
throws Exception {
byte[] a1 = InetAddress.getByName(ip1).getAddress();
byte[] a2 = InetAddress.getByName(ip2).getAddress();
byte[] m = InetAddress.getByName(mask).getAddress();
for (int i = 0; i < a1.length; i++)
if ((a1[i] & m[i]) != (a2[i] & m[i]))
return false;
return true;
}
然后像这样使用它:
sameNetwork("1.2.3.4", "1.2.4.3", "255.255.255.0")
> false
编辑:
如果您已经将 IP 作为 InetAddress
对象:
public static boolean sameNetwork(InetAddress ip1, InetAddress ip2, String mask)
throws Exception {
byte[] a1 = ip1.getAddress();
byte[] a2 = ip2.getAddress();
byte[] m = InetAddress.getByName(mask).getAddress();
for (int i = 0; i < a1.length; i++)
if ((a1[i] & m[i]) != (a2[i] & m[i]))
return false;
return true;
}
关于java - 使用Java测试两个IP是否在同一个网络中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8555847/