【问题标题】:PHP Check if IP Address is in a range of IP AddressesPHP检查IP地址是否在IP地址范围内
【发布时间】:2013-08-22 14:43:59
【问题描述】:

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

所以我写了一些简单的东西来满足我的目的。到目前为止,它运行良好。

【问题讨论】:

标签: php range ip-address


【解决方案1】:

这是我想出的小东西。我确信还有其他方法可以检查,但这将满足我的目的。

例如,如果我想知道 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));
    }    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2017-05-28
    • 1970-01-01
    • 2012-06-22
    • 2023-03-28
    • 2021-09-08
    • 2011-09-30
    相关资源
    最近更新 更多