检测IP是否为国内IP

定期获取IP网段

这里小编写了shell脚本并且结合crontab定期获取IP网段列表并写入Redis

  1. 编写shell脚本获取IP断列表并写入redis中, 保存文件为shell.sh

    1
    2
    3
    4
    5
    6
    7
    !#/bin/bash
    curl 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | grep ipv4 | grep CN | awk -F\| '{ printf("%s/%d\n", $4, 32-log($5)/log(2)) }' > /china_ip.txt

    cat '/china_ip.txt' |while read p
    do
    redis-cli -h 127.0.0.1 -p 6379 hset "china_ip" $p $p >/dev/null
    done
  2. 在crontab 加上以下命令 (每天00:00自动更新脚本)

    1
    00 00 * * * /data/shell.sh

使用函数判断指定IP是否存在指定网段中(Laravel框架)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Class Sms
* @package App\Http\Services\Common
* @Author YiYuan-LIn
* @Date: 2019/2/28
* 校验IP工具类
*/
class VerifyIp
{
/**
* @Author YiYuan-LIn
* @Date: 2019/8/10
* @enumeration:
* @param $ip
* @return bool
* @description 校验IP是否处于国内的网段
*/
public static function CheckWhetherIPIsDomestic($ip)
{
//校验IP参数是否合法
if (empty($ip)) return false;
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) return false;
$ip = (double) (sprintf("%u", ip2long($ip)));
$china_ip = Redis::hkeys('china_ip');
$china_ip = array_filter($china_ip);
if (empty($china_ip)) return false;

foreach ($china_ip as $key => $value) {
$s = explode('/', $value);
$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;
continue ;
}

return false;
}
}
-------------本文结束感谢您的阅读-------------