Most questions I've seen regarding validating private IPs in PHP have to do with validating if a specific IP address is private or not, or whether an IP exists within a specific range.
However, I want to be able to determine in PHP whether or not an IP range, given in the format of e.g. "X.X.X.X - Y.Y.Y.Y" is an exclusively private range. Just so it's clear, I want to see if the entire range is private or not. Examples:
10.0.0.1 - 10.0.0.14
would return true since all IPs in this range are internal.
10.0.0.1 - 127.0.0.16
would return false because not all of the IPs in the range are internal/private, even though the start and end points are.
My initial thought was to just validate the start and end IPs, and if they're internal, then all good. But, as I said above, if I had a range like $range = '10.0.0.1 - 127.0.0.16'
, while the start and end IP addresses are both considered to be private IP addresses, it spans IP addresses that are not internal, hence it's not an exclusively internal IP address range.
I could perhaps generate every single IP address within the range, and validate each one, but this seems incredibly inefficient.
Is there an easier and more efficient way of doing this?
Edit: Just to make it more explicitly clear to those flagging this as a duplicate: I am not trying to validate a single given IP and see if it is private. I want to check that every single possible IP in a given range of the format $range = '10.0.0.1 - 127.0.0.16'
is private. Doing something like this is far too slow and inefficient (assuming I've exploded the string to get the start and end IP addresses):
<?php
function checkRange($start, $end)
{
$start = ip2long($start);
$end = ip2long($end);
for ($i = $start; $i <= $end; $i++) {
$ip = long2ip($i);
if (!filter_var(
$ip,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_IPV4
)) {
continue;
}
return false;
}
return true;
}