Determining if an IP is within a specific range: redux

Submarine NetI was reading Paul Gregg’s very clear explanation of “classless” ranges comparison when I realized that his code was not as “bare metal” as could be.

So, here is the code I’ve been using in nextBBS.
It only accepts ranges in the form “x.x.x.x/b” but it’s short and all I needed, really.

function isSubnet($subnet, $ip)
{
    // Classless (in more than one way) comparison
    $cursubnet = explode('/', $subnet);
    $longsubnet = ip2long($cursubnet[0]);
    $longip = ip2long($ip);
 
    if(count($cursubnet)<2)
    {
        // Compare IP itself
        return ($longip==$longsubnet);
    }
 
    // IPv4 only!
    $subnetmask = 0xffffffff << (32-$cursubnet[1]);
    return (($longip & $subnetmask) == ($longsubnet & $subnetmask));
}

Similar Posts:

If you enjoyed this post, make sure you subscribe to my RSS feed!

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)