I’m searching for a php algorithm that efficiently test if one cidr notated network overlaps another.
Basically I have the following situation:
Array of cidr adresses:
$cidrNetworks = array(
'192.168.10.0/24',
'10.10.0.30/20',
etc.
);
I have a method that adds networks to the array, but this method should throw an exception when a network is added that overlaps with a network allready in the array.
So ie. if 192.168.10.0/25 is added an exception should be thrown.
Does anyone have/know/”can think of” an method to test this efficiently?
Here is an updated version of the class previously discussed in chat. It can do what you require, as well as many other useful things.
In order to do what you desire, the class provides 4 methods:
Example usage of these:
The class also implements the
Iteratorinterface, allowing you to iterate over all the addresses in a subnet. The iterator excludes the network and broadcast addresses, which can be retrieved separately.Example:
The class also implements
ArrayAccess, allowing you to treat it as an array:NB: The iterator/array methods of accessing the subnet’s host addresses will return another
IPv4Subnetobject. The class implements__toString(), which will return the IP address as a dotted decimal if it represents a single address, or the CIDR if it represents more than one. The data can be accessed directly as a string or an integer by calling the relevantget*()method and passing the desired flag(s) (see constants defined at the top of the class).All operations are 32- and 64-bit safe. Compatibility should be (although not thoroughly tested) 5.2+
See it working
For completeness, I imagine your use case would be implemented something along these lines:
See it working