1 """IP address set manipulation, built on top of ipaddr.py"""
3 # Copyright 2014 Ian Jackson
5 # This file is Free Software. It was originally written for secnet.
7 # You may redistribute it and/or modify it under the terms of the GNU
8 # General Public License as published by the Free Software
9 # Foundation; either version 2, or (at your option) any later
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 "A set of IP addresses"
29 def __init__(self
,l
=[]):
30 "New set contains each ipaddr.IPNetwork in the sequence l"
36 # housekeeping and representation
39 self
._v
[v
] = ipaddr
.collapse_address_list(self
._v
[v
])
41 return "IPAddressSet(%s)" % self
.networks()
42 def str(self
,comma
=",",none
="-"):
43 "Human-readable string with controllable delimiters"
45 return comma
.join(map(str, self
.networks()))
53 "Appends each ipaddr.IPNetwork in the sequence l to self"
58 "Appends each ipaddr.IPNetwork in the sequence l to self"
60 self
._v
[a
.version
].append(a
)
62 # enquirers including standard comparisons
63 def __nonzero__(self
):
69 def __eq__(self
,other
):
71 if self
._v
[v
] != other
._v
[v
]:
74 def __ne__(self
,other
): return not self
.__eq__(other
)
75 def __ge__(self
,other
):
76 """True iff self completely contains IPAddressSet other"""
78 if not self
._contains_net(o
):
81 def __le__(self
,other
): return other
.__ge__(self
)
82 def __gt__(self
,other
): return self
!=other
and other
.__ge__(self
)
83 def __lt__(self
,other
): return other
.__gt__(self
)
85 def __cmp__(self
,other
):
86 if self
==other
: return 0
87 if self
>=other
: return +1
88 if self
<=other
: return -1
92 "Iterates over minimal list of distinct IPNetworks in this set"
98 "Returns miminal list of distinct IPNetworks in this set"
99 return [i
for i
in self
]
102 def intersection(self
,other
):
103 "Returns the intersection; does not modify self"
107 for j
in other
._v
[v
]:
109 if i
.prefixlen
> j
.prefixlen
:
114 def union(self
,other
):
115 "Returns the union; does not modify self"
117 r
._append(self
.networks())
118 r
._append(other
.networks())
122 def _contains_net(self
,n
):
123 """True iff self completely contains IPNetwork n"""
125 if i
.overlaps(n
) and n
.prefixlen
>= i
.prefixlen
:
129 def contains(self
,thing
):
130 """Returns True iff self completely contains thing.
131 thing may be an IPNetwork or an IPAddressSet"""
137 return self
._contains_net(ipaddr
.IPNetwork(thing
))
139 return self
.__ge__(thing
)
142 "Returns a set containing all addresses"
145 a
=ipaddr
.IPAddress(0,v
)
146 n
=ipaddr
.IPNetwork("%s/0" % a
)