校验表单填入IP信息是否符合192.168.100.100------192.168.0/24------192.168.100.1-192.168.100.50三种ip形式

import re
import socket    

def ip_is_legal(ip_str):
    compile_ip = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
    if compile_ip.match(ip_str):
        pass
    elif compile_ip.match(ip_str.split("/")[0]) and 0 < int(ip_str.split("/")[-1]) <= 32:
        pass
    elif compile_ip.match(ip_str.split("-")[0]) and compile_ip.match(ip_str.split("-")[-1]) and int(
            socket.inet_aton(ip_str.split("-")[0]).encode('hex'), 16) < int(
            socket.inet_aton(ip_str.split("-")[-1]).encode('hex'), 16):
        pass
    else:
        raise exceptions.ValidationError(ip_str + ': 不是有效的ip或ip段')

检测ip是否属于某个ip段

import IPy


def ip_check(ip, whitelists):
    for whitelist in whitelists:
        try:
            if '-' not in whitelist:
                if ip in IPy.IP(whitelist):
                    in_whitelist = True
                else:
                    in_whitelist = False
            else:
                iplist = whitelist.split('-')
                if IPy.IP(iplist[0]) <= IPy.IP(ip) <= IPy.IP(iplist[-1]):
                    in_whitelist = True
                else:
                    in_whitelist = False
        except:
            in_whitelist = False

        if in_whitelist:
            break

    return in_whitelist


ip = "192.168.100.84"
whitelists = "192.168.100.0/24"

results = ip_check(ip, whitelists)

 

你可能感兴趣的:(校验表单填入IP信息是否符合192.168.100.100------192.168.0/24------192.168.100.1-192.168.100.50三种ip形式)