Search code examples
pythoncidr

Find subtract IPSet


I would like to be able to get an ip filter using netaddr in python but I don't know how to subtract two ips to create on CIDR range. Instead I am getting two separate ranges.

from netaddr import *

allnets = IPSet(['0.0.0.0/0'])
ip = IPSet(['8.8.8.8', '8.8.8.4'])

for ips in ip:
     print allnets - ip

I would like to get one IPset object that filters both ips, not two sets of ranges that filter each ip.


Solution

  • The expression you are searching for is allnets - ip. That produces "one IPset object that filters both ips".

    Consider this program:

    from netaddr import *
    
    allnets = IPSet(['0.0.0.0/0'])
    ip = IPSet(['8.8.8.8', '8.8.8.4'])
    filtered = allnets - ip
    
    assert '8.8.8.8' not in filtered
    assert '8.8.8.4' not in filtered
    assert '8.8.8.7' in filtered
    assert '192.0.2.17' in filtered
    assert '203.0.113.1' in filtered