PHP检查IP地址是否在IP地址范围内

Rud*_*dom 0 php ip-address range

我的任务是检查给定的IP地址是否在IP地址范围之间.例如,IP地址10.0.0.10是否在10.0.0.1和10.0.0.255范围内.我正在寻找一些东西,但我无法找到适合这种确切需求的东西.

所以我写了一些简单的东西,它符合我的目的.到目前为止,它运作良好.

Rud*_*dom 12

这是我想出的小事.我相信还有其他方法可以检查,但这样做可以达到我的目的.

例如,如果我想知道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")); 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它返回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));
    }    
Run Code Online (Sandbox Code Playgroud)