The Nexus
Show navigation Hide navigation
  • BLOG
  • ABOUT
    • Ego Surfing
  • PROJECTS
    • n2
    • S2ajax
    • Condo
    • ezEdit
    • FreeBlog - Air
    • Tooredo Alpha
    • Tools
    • Journlr, Again!
30 Apr 2009 | 1 min. (97 words)

Determining if an IP is within a specific range: redux

Submarine Net I 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){
        // Compare IP itself
        return ($longip==$longsubnet);
    }
    // IPv4 only!
    $subnetmask = 0xffffffff << (32-$cursubnet[1]);
    return (($longip & $subnetmask) == ($longsubnet & $subnetmask));
}

Comments powered by Talkyard.

Twitterified Client now fully Open-Source

Bespin in Titanium: From The Jaws Of Victory...

2022 The Nexus