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

时间:2013-10-07 11:56:56

标签: php ip

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

我该怎么做?

2 个答案:

答案 0 :(得分: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;
}

}

答案 1 :(得分:0)

我解决了。

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

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