Skip to content

Instantly share code, notes, and snippets.

@nacx
Last active March 22, 2024 17:32
Show Gist options
  • Save nacx/8837081716c5b333d7edc8bec4684482 to your computer and use it in GitHub Desktop.
Save nacx/8837081716c5b333d7edc8bec4684482 to your computer and use it in GitHub Desktop.
Network overlapping check
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"));
}
@gaurangmhatre
Copy link

@nacx Thanks, this was helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment