I am trying to figure out what the best/most efficient way to get individual /24 IP blocks from a range of IP addresses using PHP.
I have ranges of IP addresses in an MySQL database (I cannot change how this is presented) and have to have individual ranges of /24 blocks saved, also in a specific way (I cannot change the MySQL entries, nor how the software processes the list).
For example, I have various ranges of IPv4 IP addresses in this format:
86.111.160.0 - 86.111.175.255
Which I need to save in this specific format to represent each /24 block in the range of given addresses:
86.111.160.0 86.111.161.0 86.111.162.0 ... 86.111.175.0
I’m having a bit of a block on how to do this without writing something hugely complicated to process each line.
Is there any function in PHP that can help me with this?
Thanks in advance.
Advertisement
Answer
Here is the example off of https://www.php.net/manual/en/ref.network.php#74656
A simple and very fast function to check against CIDR.
This example takes into account your range parameter
Here it is (only with arithmetic operators and call only to ip2long () and split() ):
<?php function ipCIDRCheck ($IP, $CIDR) { list ($net, $mask) = explode("/", $CIDR); $ip_net = ip2long ($net); $ip_mask = ~((1 << (32 - $mask)) - 1); $ip_ip = ip2long ($IP); $ip_ip_net = $ip_ip & $ip_mask; return long2ip($ip_ip_net); } $range = "86.111.160.0 - 86.111.175.255"; list($lower,$upper) = explode('-',$range); $lowerIp = ip2long(trim($lower)); $upperIp = ip2long(trim($upper)); while($lowerIp <= $upperIp){ echo ipCIDRCheck(long2ip($lowerIp),long2ip($lowerIp) .'/24') . "nr"; $lowerIp += 255; }