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))
相关推荐
阿尔的代码屋2 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者20 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者20 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh21 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅21 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django