如何根据子网掩码测试两个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则不在同一网络中。
答案 0 :(得分:14)
试试这个方法:
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;
}
答案 1 :(得分:5)
足够简单:mask & ip1 == mask & ip2
- 您必须将所有IP解释为单个数字,但这应该是显而易见的。
答案 2 :(得分:0)
此解决方案也适用于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);
}