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"));
}
@nacx
Copy link
Author

nacx commented Jan 7, 2020

Why Maven or Gradle and not Ant or plain javac?
This is not an OSS project. Just a code snippet without any context that I added here for further reference. There is no intent in making this usable to the rest of the world, thus it has no comments, env, context or anything else.
And it will remain like this.

Thanks for your unsolicited, useless, non-constructive comment! Hope you're not having a too much hard time trying to build this.

@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