判断指定IP是否在指定IP段中

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21682469/article/details/80394544

最近在做一个访问控制的功能,只允许指定IP,或者IP段中的IP访问。
下面方法用来判断指定IP是否在指定IP段中(已通过测试)。

/**
 * 判断IP是否在某个网段内
 * @param $ip
 * @param $network
 * @return bool
 */
function ipInNetwork($ip, $network)
{
    $ip = (double) (sprintf("%u", ip2long($ip)));
    $s = explode('/', $network);
    $network_start = (double) (sprintf("%u", ip2long($s[0])));
    $network_len = pow(2, 32 - $s[1]);
    $network_end = $network_start + $network_len - 1;

    if ($ip >= $network_start && $ip <= $network_end) {
        return true;
    }
    return false;
}

同时在使用中,发现了一个PHP内置方法hash_equals(stringa, stringb) 用来判断两个字符串是否想等。文档如下:

/**
 * Timing attack safe string comparison
 * @link http://php.net/manual/en/function.hash-equals.php
 * @param string $known_string <p>The string of known length to compare against</p>
 * @param string $user_string <p>The user-supplied string</p>
 * @return boolean <p>Returns <b>TRUE</b> when the two strings are equal, <b>FALSE</b> otherwise.</p>
 * @since 5.6.0
 */
function hash_equals($known_string, $user_string) {}

参考:https://blog.csdn.net/nxgg8/article/details/49844853

猜你喜欢

转载自blog.csdn.net/qq_21682469/article/details/80394544