Skip to content

Instantly share code, notes, and snippets.

@ripples-alive
Last active December 18, 2016 21:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ripples-alive/79a30f311295500afe78 to your computer and use it in GitHub Desktop.
Save ripples-alive/79a30f311295500afe78 to your computer and use it in GitHub Desktop.
Fetch China IPv4 list from APNIC and generate corresponding ipset command.
#!/usr/bin/env python
# coding:utf-8
import re
import math
import urllib2
def fetch_ip_data():
#fetch data from apnic
url=r'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
data=urllib2.urlopen(url).read()
cnregex=re.compile(r'apnic\|cn\|ipv4\|[0-9\.]+\|[0-9]+\|[0-9]+\|a.*',re.IGNORECASE)
cndata=cnregex.findall(data)
ip_data=[]
for item in cndata:
unit_items=item.split('|')
starting_ip=unit_items[3]
num_ip=int(unit_items[4])
imask=0xffffffff^(num_ip-1)
#convert to string
imask=hex(imask)[2:]
mask=[0]*4
mask[0]=imask[0:2]
mask[1]=imask[2:4]
mask[2]=imask[4:6]
mask[3]=imask[6:8]
#convert str to int
mask=[ int(i,16 ) for i in mask]
mask="%d.%d.%d.%d"%tuple(mask)
#mask in *nix format
mask2=32-int(math.log(num_ip,2))
ip_data.append((starting_ip,mask,mask2))
return ip_data
ip_data = fetch_ip_data()
for ip, mask, mask_len in ip_data:
print 'ipset -A china_list %s/%d' % (ip, mask_len)
# Check whitelist
ipset destroy china_list
ipset -N china_list nethash
iptables -t nat -A SHADOWSOCKS -m set --match-set china_list dst -j RETURN
# Anything else should be redirected to shadowsocks's local port
iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 23333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment