How to use PHP code to determine whether an IP is within the IP segment?

To use PHP code to determine whether an IP is within the IP segment, you can use the ip2long function to convert the IP address into an integer, and then compare the sizes. The following is the implementation code:

/**
 * 判断某个 IP 是否在 IP 段内
 *
 * @param string $ip IP 地址
 * @param string $startIp 起始 IP
 * @param string $endIp 结束 IP
 * @return bool
 */
function inIpRange($ip, $startIp, $endIp)
{
    $ipInt = ip2long($ip);
    $startIpInt = ip2long($startIp);
    $endIpInt = ip2long($endIp);
    return ($ipInt >= $startIpInt && $ipInt <= $endIpInt);
}

When calling, pass in the IP address to be judged, the start address and the end address of the IP segment, and the function will return a Boolean value indicating whether the IP address is within the specified IP segment.

You can use PHP's built-in ip2long function to convert the IP address into an integer, then convert the starting IP and ending IP of the IP segment into integers respectively, and finally determine whether the IP integer to be determined is within the range of the IP segment. The following is the implementation code:

function isIpInRange($ip, $start, $end)
{
    
    
    if (filter_var($ip, FILTER_VALIDATE_IP) && filter_var($start, FILTER_VALIDATE_IP) && filter_var($end, FILTER_VALIDATE_IP)) {
    
    
        $startLong = ip2long($start);
        $endLong = ip2long($end);
        $ipLong = ip2long($ip);
        if ($ipLong >= $startLong && $ipLong <= $endLong) {
    
    
            return true;
        }
    }
    return false;
}

Call the isIpInRange($ip, $start, $end) function and pass in the IP address to be determined, the starting IP and the ending IP of the IP segment. The function will return a Boolean value indicating whether the IP to be determined is within the specified IP segment range. . It should be noted that this function only works with IPv4 addresses.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/132845269