我的任务是检查给定的 IP 地址是否在 IP 地址范围之间。例如 IP 地址 10.0.0.10 是否在 10.0.0.1 和 10.0.0.255 的范围内。我一直在寻找一些东西,但我找不到适合这种确切需求的东西。
所以我写了一些简单的东西来满足我的目的。到目前为止,它运行良好。
我的任务是检查给定的 IP 地址是否在 IP 地址范围之间。例如 IP 地址 10.0.0.10 是否在 10.0.0.1 和 10.0.0.255 的范围内。我一直在寻找一些东西,但我找不到适合这种确切需求的东西。
所以我写了一些简单的东西来满足我的目的。到目前为止,它运行良好。
这是我想出的小事。我相信还有其他方法可以检查,但这将符合我的目的。
例如,如果我想知道 IP 地址 10.0.0.1 是否介于 10.0.0.1 和 10.1.0.0 之间,那么我将运行以下命令。
var_dump(ip_in_range("10.0.0.1", "10.1.0.0", "10.0.0.1"));
在这种情况下,它返回 true 以确认 IP 地址在该范围内。
# We need to be able to check if an ip_address in a particular range
function ip_in_range($lower_range_ip_address, $upper_range_ip_address, $needle_ip_address)
{
# Get the numeric reprisentation of the IP Address with IP2long
$min = ip2long($lower_range_ip_address);
$max = ip2long($upper_range_ip_address);
$needle = ip2long($needle_ip_address);
# Then it's as simple as checking whether the needle falls between the lower and upper ranges
return (($needle >= $min) AND ($needle <= $max));
}