1、验证是否为IP地址
def isIP(ip, with_netmask=True): """ 判断IP的格式是否正确 :param ip: IP字符串 :param with_netmask: 后面是否携带 ‘/24‘的掩码 :return: """ if with_netmask: p = re.compile(‘^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?/(\d|[1]?\d?|2?[0-4]?))$‘) else: p = re.compile(‘^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?/(\d|[1]?\d?|2?[0-4]?))$‘) if p.match(ip): return True else: return False
判断是否为IP
2、将数字转化为掩码
1 def num2netmask(num): 2 """ 3 将24转化为255.255.255.0 4 :param num: 数字 5 :return: 掩码 6 """ 7 if num > 32 or num <= 0: 8 return None 9 netmask_str = ‘1‘ * num + ‘0‘ * (32 - num) 10 netmask_list = [netmask_str[i:i + 8] for i in range(0, len(netmask_str), 8)] 11 netmask = ‘.‘.join(str(int(netmask_slice, base=2)) for netmask_slice in netmask_list) 12 return netmask
数字转化为掩码
时间: 2024-10-11 17:16:33