且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:如何检测IPv6在IPV6范围内?

更新时间:2023-01-20 23:15:39

检查地址是否在范围内的最简单方法是将地址和范围的限制转换为二进制,然后使用常规比较运算符:

The easiest way to check if an address is in a range is to convert the address and the limits of the range to binary and then use normal compare operators:

$first_in_range = inet_pton('2001:db8::');
$last_in_range = inet_pton('2001:db8::ffff:ffff:ffff:ffff');

$address = inet_pton($_SERVER['REMOTE_ADDR']);

if ((strlen($address) == strlen($first_in_range))
&&  ($address >= $first_in_range && $address <= $last_in_range)) {
    // In range
} else {
    // Not in range
}