provare questo metodo:
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;
}
e usarlo in questo modo:
sameNetwork("1.2.3.4", "1.2.4.3", "255.255.255.0")
> false
EDIT:
Se hai già gli IP come InetAddress
oggetti:
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;
}
fonte
2011-12-19 00:15:14
Ma come ottenere la maschera? E funziona anche per IPv6? – xZise
@xZise La maschera è la maschera di sottorete. E sicuramente funzionerà per IPv6 altrettanto bene - solo una notazione diversa rispetto a IPv4. Ma alla fine basta usare la subnet mask per mascherare la parte di rete dell'IP e quindi confrontarle tra loro. – Voo
Ma come ottenere la maschera di sottorete dal programma stesso? – xZise