/*校验客户端ip是否是允许范围内*/
public function checkIp(){
if (Session::get('allowaccess')) {
return true;
}
$model = new ItemModel();
$asInfo = $model->getInfoBy(['code'=>'ALLOW_SERVICE','group_code'=>'SECURITY']);
$enable = $asInfo['value'] ?? '';
if ($enable != 1) {
Session::set('allowaccess',true);
$model = null;
return true;
}
$info = $model->getInfoBy(['code'=>'MANAGE_HOST','group_code'=>'SECURITY']);
$hosts = explode("\n",$info['value']);//分割字符串
$ip = $this->getHostIp();
$tagvar = false;
foreach ($hosts as $key=>$val){
//去除换行符
$arval = rtrim($val);
$indexFile = '';
//优先匹配ip 否,校验ip属于哪个网段下的
if (strpos($arval, "/") === false){
//匹配相同的ip
if($arval == $ip)
{ $tagvar = true; continue;}
}else{
//匹配网段下所属IP
$varipnet = $this->ip_in_network($ip,$arval);
if($varipnet)
{ $tagvar = true; continue;}
}
}
if($tagvar == true){
Session::set('allowaccess',true);
}else{
Session::set('allowaccess',false);
}
$model = null;
return $tagvar;
}
/*
* 获取客户端IP地址
*
*/
public function getHostIp()
{
//tp内置函数获取客户端ip
$IP = request()->ip();
return $IP;
}
/**
* 判断IP是否在某个网段内
* @param $ip 10.0.0.135 本机ip地址
* @param $network 10.0.0.0/24
*/
public 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;//本机ip属于这个网段返回结果为1
}
return false;//本机ip属于这个网段返回结果为0
}