一 获取国内ip地址
wget -q --timeout=60 -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk -F| '/CN|ipv4/ { printf("%s/%d
", $4, 32-log($5)/log(2)) }' > /root/china_ssr.txt
2020-6-28最新的ip列表
链接:https://pan.baidu.com/s/1428CL-I7XPl8PeAzhi4Jog
提取码:c0fp
二、防火墙添加ip列表
centos6下 allcn.sh
mmode=$1
#下面语句可以单独执行,不需要每次执行都获取网段表
#wget -q --timeout=60 -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk -F| '/CN|ipv4/ { printf("%s/%d
", $4, 32-log($5)/log(2)) }' > /root/china_ssr.txt
CNIP="/root/china_ssr.txt"
#获取ip列表
gen_iplist() {
cat <<-EOF
$(cat ${CNIP:=/dev/null} 2>/dev/null)
EOF
}
#清空
flush_r() {
iptables -F ALLCNRULE 2>/dev/null
iptables -D INPUT -p tcp -j ALLCNRULE 2>/dev/null
iptables -X ALLCNRULE 2>/dev/null
ipset -X allcn 2>/dev/null
}
mstart() {
ipset create allcn hash:net 2>/dev/null
ipset -! -R <<-EOF
$(gen_iplist | sed -e "s/^/add allcn /")
EOF
iptables -N ALLCNRULE
iptables -I INPUT -p tcp -j ALLCNRULE
iptables -A ALLCNRULE -s 127.0.0.0/8 -j RETURN
iptables -A ALLCNRULE -s 169.254.0.0/16 -j RETURN
iptables -A ALLCNRULE -s 224.0.0.0/4 -j RETURN
iptables -A ALLCNRULE -s 255.255.255.255 -j RETURN
#start可在此增加你的公网网段,避免调试ipset时出现自己无法访问的情况
#end
iptables -A ALLCNRULE -m set --match-set allcn src -j RETURN
iptables -A ALLCNRULE -p tcp -j DROP
}
if [ "$mmode" == "stop" ] ;then
flush_r
exit 0
fi
flush_r
sleep 1
mstart
centos7下 allcn.sh
三、nginx添加ip白名单
location /{
include /home/whitelist.conf;
deny all;
}
#whitelist.conf 内容
allow 117.124.0.0/9;
allow 116.128.0.0/9;
allow 39.128.0.0/10;
...
#当然,whitelist.conf 中的内容也可以直接写在 nginx.conf 里
四、程序中添加限制,接口响应影响访问速度
php是否国内ip
function isIpAllow() {
$ip = "";
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = trim(current(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
} elseif(!empty($_SERVER['REMOTE_ADDR']) ) {
$ip = $_SERVER['REMOTE_ADDR'];
}
$ip = preg_match ( '/[d.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
if($ip)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://ip-api.com/json/".$ip."?fields=country");
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
if( !empty($data) && strpos( strtolower($data),'china')=== false)
{
return false;
}
return true;
}
return true;
}
ip的参考文章
https://www.cnblogs.com/lushaoyan/p/11088213.html
https://www.cnblogs.com/rendd/p/6183094.html