Categories
Programmierung

PHP: IP ranges überprüfen

Quick and dirty PHP-Script zum überprüfen ob eine IP-Adresse in einem angegebenen IP-Range ist.


$ranges = array(
    "10.10.10.2-4",
    "192.168.0-255.0-255",
    "10.20.0.1",
    );

if (inIpRange("10.10.10.3", $ranges)) {
    echo "bingo!";
}

function inIpRange($needle, $haystack) {

    if (!is_array($haystack)) {
        $haystack = array($haystack);
    }

    foreach ($haystack as $ip) {

        $d = explode('.', $ip);
        $r = explode('.', $needle);

        foreach ($d as $key => $num) {

            if (strpos($num, '-') !== false) {
                $range = explode('-', $num);

                if ($r[$key] < $range[0] || $r[$key] > $range[1]) {
                    continue 2;
                }
            } elseif ($num != $r[$key]) {
                continue 2;
            }
        }

        return true;
    }

    return false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.