2013-08-20 226 views
0

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

所以我写了一些简单的东西,用于我的目的。到目前为止,它工作得很好。

+0

你如何指定你的地址范围? – Anigel

+0

在问题主体中提供更多详细信息,这是一个很好的问答 –

+0

是否要获取IP的子网范围,或检查检测到的地址是否位于指定数组内? –

回答

10

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

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