使用 ip2long 比较 IP 范围

IP range comparison using ip2long

我正尝试按照本教程中的说明使用 ip2long 来编译 IP: How to check an IP address is within a range of two IPs in PHP?

代码如下:

$ip2 = ip2long("127.0.0.1");
$high_ip = ip2long("128.0.0.0");
$low_ip = ip2long("126.0.0.1");
if ($ip2 <= $high_ip && $low_ip <= $ip2) {
  echo "in range";
}
else {
    echo "no";
}

我已经尝试切换高 IP 和低 IP,但仍然得到相同的结果。

为什么我的脚本无法检测到 IP 实际上在范围内?

注意:我需要将用户的 IP 与广泛的范围进行比较,例如:1.1.2.0 - 1.2.2.0。

您的代码有错误: $ip2 未定义。 这将是 : 如果($ip <= $high_ip && $low_ip <= $ip){

你必须使用 sprintf("%u", $ip),像这样:

if (sprintf("%u", $ip) <= sprintf("%u", $high_ip)  && sprintf("%u", $low_ip) <= sprintf("%u", $ip))

为什么?如果您查看手册:http://php.net/manual/en/function.ip2long.php

你会明白为什么的:

Note: Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

编辑:

开始:

Good to know, but for what evil reason is it working properly here? prntscr.com/6i0o82 Because it might not be a 32-bit architecture? – briosheje 12 mins ago

是的 ^ 在网上 IDE 它可以工作,因为它是 64 位架构。正如上面关于 32 位体系结构的引用中提到的,这将不起作用,因为它会导致负整数,所以这就是为什么你必须使用 %u + sprintf()printf()

我有哪种架构?

您可以简单地这样做:

echo PHP_INT_MAX;

2147483647          -> 32 bit
9223372036854775807 -> 64 bit

编辑 2:

也来自 :

btw I am using xampp, but it shouldn't matter in this case? – user1721135 22 mins ago

PHP 在 windows 上不支持 64 位,或者至少不是官方的。您可以在此处see/read:http://windows.php.net/

引自那里:

x86_64 Builds The x64 builds of PHP for Windows should be considered experimental, and do not yet provide 64-bit integer or large file support. Please see this post for work ongoing to improve these builds.

所以你可能在 windows 上使用 xampp 而 php 64 位版本没有 xampp:

如果您没有在 windows 上使用 xampp,您可以在此处下载 xampp 64 位 php MAC 和 linux : https://www.apachefriends.org/download.html