2

我有大约 1000 个 IP 地址。我使用下面的代码为他们计算 IP 范围:

public function ipRange($mainIp, $mask)
{
    $mainIpLong = ip2long($mainIp);
    $maskLong = ip2long($mask);

    $netid = long2ip($mainIpLong & $maskLong);
    $broadcast = long2ip($mainIpLong | ~$maskLong);

    //here I insert $netid and $broadcast to a MySQL table
    //so I have abount 1000 records
}

它正确计算 IP 范围,例如,如果我这样调用:

ipRange('91.99.98.243', '255.255.255.240');

结果将是:

$netid     -> 91.99.98.240
$broadcast -> 91.99.98.255

现在我需要一个搜索功能。它应该找到给定 IP 地址的子范围,所以如果我调用search('91.99.98.249'),search() 函数应该显示 netid 为 91.99.98.240 和广播字段为 91.99.98.255 的记录。

我怎样才能做到这一点?

4

2 回答 2

0
function find($ip){
//get $netid and $bcast from db one by one
//loop through all records
if(ip2long($ip)>=ip2long($netid) && ip2long($ip)<=ip2long($bcast) ){
echo $netid;
echo $bcast;
}

}
于 2013-10-08T04:36:46.227 回答
0

我解决了。

注意:_getConnection()函数连接到数据库。 ip_address字段包括:IP、netid 和广播。

public function search($ip)
{
    $ranges = $this->_getConnection()->fetchAll("SELECT netid, broadcast FROM ip_address");

    foreach($ranges as $range) {
        $min = ip2long($range['netid']);
        $max = ip2long($range['broadcast']);

        if(ip2long($ip) > $min && ip2long($ip) < $max) {
            $result = $this->_getConnection()->fetchAll("SELECT * FROM ip_address WHERE netid = ? AND broadcast = ?", array($range['netid'], $range['broadcast']));
        }
    }

    return $result;
}
于 2013-10-08T13:17:20.680 回答