python ip操作

2017/7/30 posted in  python

根据ip段取所有ip

from IPy import IP
ip = IP('192.168.0.0/24')
print ip.len()

for i in ip:
   print i

计算ip是否在指定的段中

from IPy import IP
ip = IP('192.168.0.0/24')
print IP('192.168.0.132') in ip

django校验来源ip是否在配置的白名单中


iplist = """192.168.1.0/24
192.168.1.64/26
10.0.1.0/25
127.0.0.1"""

# 加载ip列表,本算法是应对配置的ip量较大的情况
# 将ip的A\B\C段做为key,ip做为value,生成一个dict,提升校验速度
# {
#   '192.168.1': [IP('192.168.1.2'), 
#                 IP('192.168.1.3'), 
#                 IP('192.168.1.4')]
#   '127.0.0': [IP('127.0.0.1')]
# }
def loadip():
    res = {}
    for ipstring in iplist.split("\n"):
        # 提取ip的ABC段
        key = '.'.join(ipstring.split('.')[:3])
        if key not in res:
            res[key] = []

        ips = IP(ipstring)
        for ip in ips:
            # print ip
            res[key].append(ip)

    return res

# 校验request是否是合法来源
def _check_request(request):
    ipwhitelist = loadip()
    remoteip = request.META['REMOTE_ADDR']
    key = '.'.join(remoteip.split(".")[:3])
    remoteip = IP(remoteip)

    if key not in ipwhitelist:
        return False

    if remoteip not in ipwhitelist[key]:
        return False
    return True