PHP to determine whether a particular IP within the network

Sometimes the need to determine whether a particular IP within a certain range, for a subnetting network, one is difficult to judge, starting and ending with the end of the need to calculate subnet addresses for CCNA learned knowledge may not be clearly counted. Look at the code:
<?php
/**
	* 判断IP是否在某个网络内
	* 运维生存时间
	* site:www.ttlsa.com

	* @param $ip
	* @param $network
	* @return bool
*/

function ip_in_network($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;
}

?>
This method can be used as a common function. Long-winded one, put the case for the IP address stored in the database, strongly recommends that you use ip2long then converted into a database. For reprint please indicate the source: http: //www.ttlsa.com/html/2751.html

Reproduced in: https: //my.oschina.net/766/blog/211135

Guess you like

Origin blog.csdn.net/weixin_33725515/article/details/91547166