简体   繁体   中英

How to search an IP in an IP range using PHP?

I have about 1000 IP address. I calculate IP ranges for them using the bellow code:

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
}

It calculates IP range correctly, for example if I call like this:

ipRange('91.99.98.243', '255.255.255.240');

Result will be:

$netid     -> 91.99.98.240
$broadcast -> 91.99.98.255

Now I need to have a search function. It should find the sub-range for the given IP address, so if I call search('91.99.98.249') , the search() function should show the record that netid is 91.99.98.240 and broadcast field is 91.99.98.255.

How can I do that?

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

}

I solved it.

Note: _getConnection() function connects to database. ip_address fields includes: IP, netid and broadcast.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM