php 8.6判断地址是否位于ipv4或ipv6网段时,可用inet_pton转换为二进制,再比较完整字节和最后一个部分字节。不要把ipv6强行转成32位整数;地址族不同直接不匹配,输入地址应来自可信连接信息。
。图源:PHP Documentation Group(CC BY 3.0)。
PHP手册中的inet_pton。图源:PHP Documentation Group(CC BY 3.0)。
同时处理两种地址长度
<?php function inCidr(string $ip,string $cidr):bool {
$parts=explode('/',$cidr);
if (count($parts)!==2 || !ctype_digit($parts[1])) {
throw new InvalidArgumentException('服务端CIDR配置错误');
}
$net=inet_pton($parts[0]);$addr=inet_pton($ip);
if ($net===false) throw new InvalidArgumentException('网段地址无效');
$bits=(int)$parts[1];$length=strlen($net);
if ($bits<0 || $bits>$length*8) throw new InvalidArgumentException('前缀越界');
if ($addr===false || strlen($addr)!==$length) return false;
$whole=intdiv($bits,8);$rest=$bits%8;
if (substr($addr,0,$whole)!==substr($net,0,$whole)) return false;
if ($rest===0) return true;
$mask=(0xff <p style="text-align:center">@@##@@。图源:PHP Documentation Group(CC BY 3.0)。</p><p style="text-align:center">PHP手册中的inet_ntop。图源:PHP Documentation Group(CC BY 3.0)。</p><h2>验证边界而不是只测一个地址</h2><p>192.0.2.0/24应包含192.0.2.1,不包含192.0.3.1;2001:db8::/32应包含该前缀内IPv6。/0匹配相同地址族的全部地址,/32或/128只匹配一个地址。例中的网段用于文档演示,部署时替换成真实允许范围。</p><h2>先确定地址来自哪里</h2><p>反向代理场景下REMOTE_ADDR通常是代理地址。只有在服务器明确配置可信代理、并按确定规则解析转发头时,才使用转发地址;不能直接信任任意客户端X-Forwarded-For。排查表示形式时,可用inet_ntop(inet_pton($ip))观察规范化地址;这只改变显示,不决定访问权限。IPv4映射IPv6仍按16字节处理,若业务需要把它折算成IPv4,应先制定统一规范化策略。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build MCP servers and clients for PHP applications with the official PHP SDK" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="overflowclass">Build MCP servers and clients for PHP applications with the official PHP SDK</a>
<p class="overflowclass">使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>

php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










