How to check an IP address is within a range of tw

2020-01-26 04:40发布

I have an IP address and I'm given two other IP addresses which together creates an IP range. I want to check if the first IP address is within this range. How can i find that out in PHP?

标签: php ip range
8条回答
虎瘦雄心在
2楼-- · 2020-01-26 05:19
if(version_compare($low_ip, $ip) + version_compare($ip, $high_ip) === -2) {
    echo "in range";
}
查看更多
ら.Afraid
3楼-- · 2020-01-26 05:19

Here is my approach of the subject.

function validateIP($whitelist, $ip) {

    // e.g ::1
    if($whitelist == $ip) {
        return true;
    }

    // split each part of the IP address and set it to an array
    $validated1 = explode(".", $whitelist);
    $validated2 = explode(".", $ip);

    // check array index to avoid undefined index errors
    if(count($validated1) >= 3 && count($validated2) == 4) {

        // check that each value of the array is identical with our whitelisted IP,
        // except from the last part which doesn't matter
        if($validated1[0] == $validated2[0] && $validated1[1] == $validated2[1] && $validated1[2] == $validated2[2]) {
            return true;
        }   

    }

    return false;
}
查看更多
登录 后发表回答