需求
192.168.1.0/24,192.168.2.1-192.168.2.254,192.168.3.3
IP段格式已 "," 分割,获取所有IP
注意
1. 判断 IP 是否合规
2. 去除多余的字符,例如空格、换行符
3. 去重
代码
import re
import ipaddressdef isIP(ip):p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')if p.match(ip):return Trueelse:return Falsedef get_ip_last(ip):parts = ip.split(".")last_octet = int(parts[3])return last_octetdef range_to_ips(mask):try:ip_list = []ips = mask.split("-", 1)start_ip = ips[0]end_ip = ips[1]last_octet = get_ip_last(start_ip)if last_octet <= 0 or last_octet >= 255:return Falselast_octet = get_ip_last(end_ip)if last_octet <= 0 or last_octet >= 255:return Falsestart = ipaddress.IPv4Address(start_ip)end = ipaddress.IPv4Address(end_ip)for ip in range(int(start), int(end) + 1):ip_tmp = ipaddress.IPv4Address(ip)ip_list.append(str(ip_tmp))except Exception as e:return Falsereturn ip_listdef ip_segment_to_ips(ip_segment):ip_list = []ip_segment = ip_segment.strip()ip_tmp = ip_segment.split(",")for ip_range in ip_tmp:if "/" in ip_range:ips = mask_to_ips(ip_range)if not ips:return Falseelse:ip_list.extend(ips)elif "-" in ip_range:ips = range_to_ips(ip_range)if not ips:return Falseelse:ip_list.extend(ips)elif isIP(ip_range):ip_list.append(ip_range)else:passip_list = list(set(ip_list))print(ip_list, len(ip_list))return ip_listif __name__ == '__main__':ip_segment = "192.168.1.0/24,192.168.2.1-192.168.2.254,192.168.3.3"print(ip_segment_to_ips(ip_segment))
执行结果
list中