Skip to content

Instantly share code, notes, and snippets.

@technoknol
Last active September 25, 2024 06:59
Show Gist options
  • Save technoknol/ec1125b3488f252377b6852be86b191d to your computer and use it in GitHub Desktop.
Save technoknol/ec1125b3488f252377b6852be86b191d to your computer and use it in GitHub Desktop.
IP Range CIDR to ALL IP LIST
<?php
// IP Range CIDR to ALL IP LIST
// e.g. 220.78.168.0/21 to all IP list Range
$start_ip = '220.78.168.0';
$prefix = '28';
$ip_count = 1 << (32 - $prefix);
$start = ip2long($start_ip);
for ($i = 0; $i < $ip_count; $i++) {
echo $ip = long2ip($start + $i) . '<br />';
// do stuff with $ip...
}
// Output :
/*
220.78.168.0
220.78.168.1
220.78.168.2
220.78.168.3
220.78.168.4
220.78.168.5
220.78.168.6
220.78.168.7
220.78.168.8
220.78.168.9
220.78.168.10
220.78.168.11
220.78.168.12
220.78.168.13
220.78.168.14
220.78.168.15
*/
// Source: Learn IPv4 Range CIDR
// http://aprelium.com/data/doc/2/abyssws-linux-doc-html/ipformat.html
@technoknol
Copy link
Author

technoknol commented May 2, 2016

Checks if IP is in Given IP CIDR range or not.

Another logic
NOT TESTED FULLY YET


function cidr_match($ip, $cidr)
{
    list($subnet, $mask) = explode('/', $cidr);

    if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long($subnet))
    { 
        return true;
    }

    return false;
}

// Usage 
cidr_match("127.0.0.1", "127.0.0.1/32")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment