如何根据子网掩码测试两个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 ..
Ósc*_*pez 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;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
sameNetwork("1.2.3.4", "1.2.4.3", "255.255.255.0")
> false
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您已将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;
}
Run Code Online (Sandbox Code Playgroud)