【问题标题】:How can I remove two or more subnet from a network?如何从网络中删除两个或多个子网?
【发布时间】:2021-05-18 03:05:39
【问题描述】:

ipaddress 类,我知道address_exclude 方法。以下是文档中的一个示例:

>>> n1 = ip_network('192.0.2.0/28')
>>> n2 = ip_network('192.0.2.1/32')
>>> list(n1.address_exclude(n2))  
[IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
 IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]

但是如果我想从网络中删除两个或更多子网怎么办?例如,如何从 192.168.10.0/26 中删除他的子网 192.168.10.24/29 和 192.168.10.48/28?结果应该是 192.168.10.0/28、192.168.10.16/29 和 192.168.10.32/28。

我正在尝试找到一种方法来使用address_exclude 方法编写我在脑海中使用的算法,但我做不到。有没有一种简单的方法来实现我刚才解释的内容?

【问题讨论】:

    标签: python networking ipv4


    【解决方案1】:

    当您从另一个网络中排除一个网络时,结果可能是多个网络(原始网络被拆分) - 因此,对于要排除的其余网络,您需要先找到它们适合的部分,然后再将它们排除为好吧。

    这是一种可能的解决方案:

    from ipaddress import ip_network, collapse_addresses
    
    complete = ip_network('192.168.10.0/26')
    
    # I chose the larger subnet for exclusion first, can be automated with network comparison
    subnets = list(complete.address_exclude(ip_network('192.168.10.48/28')))
    # other network to exclude
    other_exclude = ip_network('192.168.10.24/29')
    
    result = []
    # Find which subnet the other exclusion will happen in 
    for sub in subnets:
        # If found, exclude & add the result
        if other_exclude.subnet_of(sub):
            result.extend(list(sub.address_exclude(other_exclude)))
        else:
        # Other subnets can be added directly
            result.append(sub)
    
    # Collapse in case of overlaps
    print(list(collapse_addresses(result)))
    

    输出:

    [IPv4Network('192.168.10.0/28'), IPv4Network('192.168.10.16/29'), IPv4Network('192.168.10.32/28')]
    

    【讨论】:

    • ciao rdas。如果我们有两个以上的子网怎么办?你能把你的逻辑放在一个函数中吗?
    • 扩展非常简单。使用循环。
    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多