将IP与PHP 5中的CIDR掩码匹配? [英] Matching an IP to a CIDR mask in PHP 5?

查看:76
本文介绍了将IP与PHP 5中的CIDR掩码匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快速/简单的方法来将给定的IP4点缀四边形IP与CIDR表示掩码匹配.

I'm looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.

我有一堆IP,我需要查看它们是否与IP范围相匹配.

I have a bunch of IPs I need to see if they match a range of IPs.

示例:

$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()是什么样的?

它不一定必须很简单,但是快速就可以了.仅使用内置/通用功能的任何东西都是一种奖励(因为我很可能会让一个人向我展示梨子中的某些东西,但这样做我不能依赖于梨子或该软件包安装在我的代码所在的位置)部署).

It doesn't really have to be simple, but fast would be good. Anything that uses only built-in/common functions is a bonus (as I'm likely to get one person to show me something in pear that does this, but I can't depend on pear or that package being installed where my code is deployed).

推荐答案

如果仅使用IPv4:

  • 使用ip2long()将IP和子网范围转换为长整数
  • 将/xx转换为子网掩码
  • 按位进行与"(即ip& mask)并检查该结果=子网"
  • use ip2long() to convert the IPs and the subnet range into long integers
  • convert the /xx into a subnet mask
  • do a bitwise 'and' (i.e. ip & mask)' and check that that 'result = subnet'

类似的东西应该起作用:

something like this should work:

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;
}

这篇关于将IP与PHP 5中的CIDR掩码匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆