如何使用PHP在IP范围内搜索IP?

用户1973756

我有大约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的记录。

我怎样才能做到这一点?

用户1973756

我解决了

注意:_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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章