gpt4 book ai didi

php - 检查 CIDR 子网是否包含 IP 地址

转载 作者:IT王子 更新时间:2023-10-28 23:55:26 25 4
gpt4 key购买 nike

我正在寻找快速/简单的方法来将给定的 IP4 点式四 IP 与 CIDR 表示法掩码匹配。

我有一堆 IP,我需要查看它们是否与某个 IP 范围匹配。

示例:

$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4');

foreach ($ips as $IP) {
if (cidr_match($IP, '10.2.0.0/16') == true) {
print "you're in the 10.2 subnet\n";
}
}

cidr_match() 会是什么样子?

它并不一定很简单,但快速会很好。任何仅使用内置/通用功能的东西都是一种奖励(因为我可能会让一个人向我展示 pear 中的一些东西,但我不能依赖 pear 或安装在我的代码所在的位置的那个包部署)。

最佳答案

如果只使用 IPv4:

  • 使用 ip2long() 将 IP 和子网范围转换为长整数
  • 将/xx 转换为子网掩码
  • 按位“与”(即 ip 和掩码)并检查“结果 = 子网”

像这样的东西应该可以工作:

function cidr_match($ip, $range)
{
list ($subnet, $bits) = explode('/', $range);
if ($bits === null) {
$bits = 32;
}
$ip = ip2long($ip);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
return ($ip & $mask) == $subnet;
}

关于php - 检查 CIDR 子网是否包含 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/594112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com