如何根据子网掩码测试两个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;
}
很简单:mask & ip1 == mask & ip2
-您必须将 IP 全部解释为一个数字,但这应该很明显。
此解决方案也适用于 IPv4/IPv6。
static boolean sameNetwork(final byte[] x, final byte[] y, final int mask) {
if(x == y) return true;
if(x == null || y == null) return false;
if(x.length != y.length) return false;
final int bits = mask & 7;
final int bytes = mask >>> 3;
for(int i=0;i<bytes;i++) if(x[i] != y[i]) return false;
final int shift = 8 - bits;
if(bits != 0 && x[bytes]>>>shift != y[bytes]>>>shift) return false;
return true;
}
static boolean sameNetwork(final InetAddress a, final InetAddress b, final int mask) {
return sameNetwork(a.getAddress(), b.getAddress(), mask);
}