Last active
March 22, 2024 17:32
-
-
Save nacx/8837081716c5b333d7edc8bec4684482 to your computer and use it in GitHub Desktop.
Network overlapping check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static boolean overlap(final String net1, final String net2) | |
{ | |
SubnetInfo subnet1 = new SubnetUtils(net1).getInfo(); | |
SubnetInfo subnet2 = new SubnetUtils(net2).getInfo(); | |
int mask1 = subnet1.asInteger(subnet1.getNetmask()); | |
int mask2 = subnet2.asInteger(subnet2.getNetmask()); | |
int maskToUse = mask1 < mask2 ? mask1 : mask2; | |
int addr1 = subnet1.asInteger(subnet1.getAddress()) & maskToUse; | |
int addr2 = subnet2.asInteger(subnet2.getAddress()) & maskToUse; | |
return addr1 == addr2; | |
} | |
public static void main(final String[] args) | |
{ | |
System.out.println(overlap("192.168.0.0/22", "192.168.0.0/24")); | |
System.out.println(overlap("192.168.1.0/22", "192.168.0.0/24")); | |
System.out.println(overlap("192.168.2.0/22", "192.168.0.0/24")); | |
System.out.println(overlap("192.168.4.0/22", "192.168.0.0/24")); | |
System.out.println(overlap("192.168.0.0/24", "192.168.0.0/24")); | |
System.out.println(overlap("192.168.0.1/24", "192.168.0.0/24")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nacx Thanks, this was helpful.