python解析ip范围,拆分为所有ip数组

代码如下,还需结合一篇文章来看:ip范围格式转换

python 复制代码
#! -*- coding:utf-8 -*
"""
@desc: 解析ip范围为单ip列表
"""

import ipaddress


def ip_range_to_list(start_ip, end_ip):
    """
    处理有明确起始ip的数据(其他类型的,可将数据转换为这种格式再使用)
    格式如下:
    192.168.0.1-192.168.255.10
    # 下面的拆分转换方法,见上一篇文章
    192.168.*.1
    192.168-169.*.*
    10.1.1.1-10
    :param start_ip:
    :param end_ip:
    :return:
    """
    # 创建起始和结束IP地址对象
    start_ip_obj = ipaddress.IPv4Address(start_ip)
    end_ip_obj = ipaddress.IPv4Address(end_ip)

    # 初始化一个空列表来存储所有的IP地址
    ip_list = []

    # 遍历范围内的所有IP地址
    current_ip = start_ip_obj
    while current_ip <= end_ip_obj:
        ip_list.append(str(current_ip))
        current_ip += 1  # 递增一个IP地址

    return ip_list


def generate_ip_list_from_cidr(cidr):
    """
    处理带掩码的数据
    192.168.1.0/24
    :param cidr:
    :return:
    """
    # 解析CIDR,得到一个IPv4Network对象,使用strict=False来允许非网络地址的IP
    network = ipaddress.IPv4Network(cidr, strict=False)

    # 计算可用的主机地址范围,network.hosts()会返回一个生成器
    ip_list = []
    for host in network.hosts():
        ip_list.append(host)

    return ip_list


if __name__ == '__main__':
    # 示例使用
    start_ip = "192.168.0.1"
    end_ip = "192.168.255.10"
    ip_list = ip_range_to_list(start_ip, end_ip)
    # 打印结果
    print(len(ip_list))


    # 定义CIDR表示的子网
    cidr = "192.168.1.0/23"
    # 调用函数并打印结果
    ip_addresses = generate_ip_list_from_cidr(cidr)
    print(len(ip_addresses))
相关推荐
用户8356290780514 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng86 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi7 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee7 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay7 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤7 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean8 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽9 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户606487671889610 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听11 小时前
RAG深入学习之Chunk
前端·人工智能·python