给定一个IP地址和一个子网,我如何使用php计算IP范围 [英] Given an IP address and a Subnet, how do I calculate the range of IPs using php

查看:91
本文介绍了给定一个IP地址和一个子网,我如何使用php计算IP范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段,我正在尝试检测IP地址是否落入某个范围内.大多数时候,我拥有IP地址和子网,但有时我仅拥有IP地址.

I have the following code snippet and im trying to detect if an IP address falls into a certain range. Most of the time I have the IP address and the subnet but sometimes I just have the IP address only.

<?php

function CalculateRange($IP,$Subnet=""){

    //Calculate subnetmax
    if ($Subnet==""){

    }        

    //Calculate max IP

    return $MaxIP;
}

//--- IP range
$IPRange = array (
    array("address"=>"196.201.26.0","subnet"=>"255.255.252.0"),
    array("address"=>"196.202.43.0","subnet"=>"255.255.0.0"),
    array("address"=>"196.203.44.0","subnet"=>"255.255.128.0"),
);

//Display MaxIP for each IP and Subnet
foreach ($IPRange as $pair) {
    echo "<p>";
    echo "For IP:{$pair['address']} with Subnet:{$pair['subnet']}.";
    echo "MaxIP is ";
    echo CalculateRange($pair['address'],$pair['subnet']);  
    echo "</p>";
}

?>

我的问题是如何为IP和子网组合计算MaxIP?

My question is how do I calculate MaxIP for the IP and Subnet combo?

推荐答案

以下内容运行正常

function isInRange() {

    //--- IP range
    $IPRange = array (
        array("address"=>"197.207.35.238","subnet"=>"255.255.0.0"),
        array("address"=>"41.207.44.232","subnet"=>"255.255.10.0"),
        array("address"=>"40.207.44.250","subnet"=>"255.255.0.0")
    );

    foreach ($IPRange as $pair) {

        //Check if we have subnet mask
        if ($pair['subnet']!='') {
            // simple example
            $bcast = ip2long($_SERVER['REMOTE_ADDR']);
            $smask = ip2long($pair['subnet']);
            $nmask = $bcast & $smask;
            $SourceStartIP = long2ip($nmask);

            if($SourceStartIP==$pair['address']) {
                //This is in range
                return true;
            }

        } else {

            //--- The header matches something in the fixed list
            if ($pair['address'] == $_SERVER['REMOTE_ADDR']) {

                return true;

            }

        }
    }

    return false;

}

这篇关于给定一个IP地址和一个子网,我如何使用php计算IP范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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