1 # This file is part of python-rwhoisd
3 # Copyright (C) 2003, 2008 David E. Blacka
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 import socket, types, copy, bisect, struct
23 """A class representing a generic CIDRized network value."""
26 def create(address, netlen = -1):
27 """Construct either a CidrV4 or CidrV6 object."""
28 if isinstance(address, int):
29 return CidrV4(address, netlen)
30 if isinstance(address, long):
31 if address <= pow(2, 32):
32 return CidrV4(address, netlen)
33 return CidrV6(address, netlen)
35 return CidrV6(address, netlen)
36 return CidrV4(address, netlen)
39 def _initialize(self, address, netlen):
40 """This a common constructor that is used by the subclasses."""
42 if isinstance(address, int) or \
43 isinstance(address, long) and netlen >= 0:
44 self.numaddr, self.netlen = address, netlen
45 self.addr = self._convert_ipaddr(address)
49 if not self.is_valid_cidr(address):
51 repr(address) + " is not a valid CIDR representation"
54 if type(address) == types.StringType:
56 self.addr, self.netlen = address.split("/", 1)
58 self.addr, self.netlen = address, self._max_netlen()
59 elif type(address) == types.TupleType:
60 self.addr, self.netlen = address
62 raise TypeError, "address must be a string or a tuple"
64 self.addr, self.netlen = address, netlen
67 # convert string network lengths to integer
68 if type(self.netlen) == types.StringType:
69 self.netlen = int(self.netlen)
74 return self.addr + "/" + str(self.netlen)
77 return "<" + str(self) + ">"
79 def __cmp__(self, other):
80 """One CIDR network block is less than another if the start
81 address is numerically less or if the block is larger. That
82 is, supernets will sort before subnets. This ordering allows
83 for an efficient search for subnets of a given network."""
85 res = self._base_mask(self.numaddr) - other._base_mask(other.numaddr)
86 if res == 0: res = self.netlen - other.netlen
92 """This method should be called after any change to the main
93 internal state: netlen or numaddr."""
95 # make sure the network length is valid
96 if not self.is_valid_netlen(self.netlen):
97 raise TypeError, "network length must be between 0 and %d" % \
100 # convert the string ipv4 address to a 32bit number
101 self.numaddr = self._convert_ipstr(self.addr)
102 # calculate our netmask
103 self.mask = self._mask(self.netlen)
104 # force the cidr address into correct masked notation
105 self.numaddr &= self.mask
107 # convert the number back to a string to normalize the string
108 self.addr = self._convert_ipaddr(self.numaddr)
110 def is_supernet(self, other):
111 """returns True if the other Cidr object is a supernet (an
112 enclosing network block) of this one. A Cidr object is a
113 supernet of itself."""
114 return other.numaddr & self.mask == self.numaddr
116 def is_subnet(self, other):
117 """returns True if the other Cidr object is a subnet (an
118 enclosednetwork block) of this one. A Cidr object is a
120 return self.numaddr & other.mask == other.numaddr
123 """return the netmask of this Cidr network"""
124 return self._convert_ipaddr(self.mask)
127 """return the length (in number of addresses) of this network block"""
128 return 1 << (self._max_netlen() - self.netlen);
131 """return the last IP address in this network block"""
132 return self._convert_ipaddr(self.numaddr + self.length() - 1)
134 def to_netblock(self):
135 return (self.addr, self.end())
138 # we can get away with a shallow copy (so far)
139 return copy.copy(self)
142 if isinstance(self, CidrV6): return True
145 def is_valid_cidr(self, address):
147 addr, netlen = address.split("/", 1)
150 addr, netlen = address, 0
151 return self._is_valid_address(addr) and self.is_valid_netlen(netlen)
153 def is_valid_netlen(self, netlen):
154 if netlen < 0: return False
155 if netlen > self._max_netlen(): return False
160 """A class representing a CIDRized IPv4 network value.
162 Specifically, it is representing a contiguous IPv4 network block
163 that can be expressed as a ip-address/network-length pair."""
165 def __init__(self, address, netlen = -1):
166 """This takes either a formatted string in CIDR notation:
167 (e.g., "127.0.0.1/32"), A tuple consisting of an formatting
168 string IPv4 address and a numeric network length, or the same
171 self._initialize(address, netlen)
173 def _is_valid_address(self, address):
174 """Returns True if the address is a legal IPv4 address."""
176 self._convert_ipstr(address)
181 def _base_mask(self, numaddr):
182 return numaddr & 0xFFFFFFFFL
184 def _max_netlen(self):
187 def _convert_ipstr(self, addr):
188 packed_numaddr = socket.inet_aton(addr)
189 return struct.unpack("!I", packed_numaddr)[0]
191 def _convert_ipaddr(self, numaddr):
192 packed_numaddr = struct.pack("!I", numaddr)
193 return socket.inet_ntoa(packed_numaddr)
195 def _mask(self, len):
196 return self._base_mask(0xFFFFFFFF << (32 - len))
200 """A class representing a CIDRized IPv6 network value.
202 Specifically, it is representing a contiguous IPv6 network block
203 that can be expressed as a ipv6-address/network-length pair."""
205 ip6_base_mask = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL # 128-bits of all ones.
206 ip6_lower_mask = 0x0000000000000000FFFFFFFFFFFFFFFFL
207 ip6_upper_mask = 0xFFFFFFFFFFFFFFFF0000000000000000L
209 def __init__(self, address, netlen = -1):
211 self._initialize(address, netlen)
213 def _is_valid_address(self, address):
215 self._convert_ipstr(address)
217 except socket.error, e:
218 print "Failed to convert address string '%s': " + str(e) % (address)
221 def _base_mask(self, numaddr):
222 return numaddr & CidrV6.ip6_base_mask
224 def _max_netlen(self):
227 def _convert_ipstr(self, addr):
228 packed_numaddr = socket.inet_pton(socket.AF_INET6, addr)
229 upper, lower = struct.unpack("!QQ", packed_numaddr);
230 return (upper << 64) | lower
232 def _convert_ipaddr(self, numaddr):
233 upper = (numaddr & CidrV6.ip6_upper_mask) >> 64;
234 lower = numaddr & CidrV6.ip6_lower_mask;
235 packed_numaddr = struct.pack("!QQ", upper, lower)
236 return socket.inet_ntop(socket.AF_INET6, packed_numaddr)
238 def _mask(self, len):
239 return self._base_mask(CidrV6.ip6_base_mask << (128 - len))
242 def valid_cidr(address):
243 """Returns the converted Cidr object if 'address' is valid CIDR
244 notation, False if not. For the purposes of this module, valid
245 CIDR notation consists of a IPv4 or IPv6 address with an optional
246 trailing "/netlen"."""
248 if isinstance(address, Cidr): return address
250 c = Cidr.create(address)
252 except (ValueError, socket.error):
255 def netblock_to_cidr(start, end):
256 """Convert an arbitrary network block expressed as a start and end
257 address (inclusive) into a series of valid CIDR blocks."""
259 def largest_prefix_v4(length):
260 # calculates the largest network length (smallest mask length)
261 # that can fit within the block length.
264 if v & 0x80000000: break
267 def largest_prefix_v6(length):
270 if v & 0x80000000000000000000000000000000L: break
273 def netlen_to_mask_v4(n):
274 # convert the network length into its netmask
275 return ~((1 << (32 - n)) - 1)
276 def netlen_to_mask_v6(n):
277 return ~((1 << (128 -n)) - 1)
279 # convert the start and ending addresses of the netblock to Cidr
280 # object, mostly so we can get the numeric versions of their
282 cs = valid_cidr(start)
285 # if either the start or ending addresses aren't valid addresses,
288 print "Invalid start or end address"
290 # if the start and ending addresses aren't in the same family, quit now
291 if cs.is_ipv6() != ce.is_ipv6():
292 print "start and end address not same family"
296 largest_prefix = largest_prefix_v6
297 netlen_to_mask = netlen_to_mask_v6
299 largest_prefix = largest_prefix_v4
300 netlen_to_mask = netlen_to_mask_v4
302 # calculate the number of IP address in the netblock
303 block_len = ce.numaddr - cs.numaddr
305 # calcuate the largest CIDR block size that fits
306 netlen = largest_prefix(block_len + 1)
308 res = []; s = cs.numaddr
310 mask = netlen_to_mask(netlen)
311 # check to see if our current network length is valid
313 # if not, shrink the network block size
316 # otherwise, we have a valid CIDR block, so add it to the list
317 cv = Cidr.create(s, netlen)
318 res.append(Cidr.create(s, netlen))
319 # and setup for the next round:
320 cur_len = netlen_to_length(netlen)
323 netlen = largest_prefix(block_len + 1)
327 if __name__ == "__main__":
329 a = Cidr.create("127.00.000.1/24")
330 b = Cidr.create("127.0.0.1", 32)
331 c = Cidr.create("24.232.119.192", 26)
332 d = Cidr.create("24.232.119.0", 24)
333 e = Cidr.create("24.224.0.0", 11)
334 f = Cidr.create("216.168.111.0/27");
335 g = Cidr.create("127.0.0.2/31");
336 h = Cidr.create("127.0.0.16/32")
337 i = Cidr.create("3ffe:4:201e:beef::0/64");
338 j = Cidr.create("2001:3c01::/32")
344 bad = Cidr.create("24.261.119.0", 32)
345 except ValueError, x:
348 print "cidr:", a, "num addresses:", a.length(), "ending address", \
349 a.end(), "netmask", a.netmask()
351 print "cidr:", j, "num addresses:", j.length(), "ending address", \
352 j.end(), "netmask", j.netmask()
354 clist = [a, b, c, d, e, f, g, h, i , j]
355 print "unsorted list of cidr objects:\n ", clist
359 print "sorted list of cidr object:\n ", clist
362 netblocks = [ ("192.168.10.0", "192.168.10.255"),
363 ("192.168.10.0", "192.168.10.63"),
364 ("172.16.0.0", "172.16.127.255"),
365 ("24.33.41.22", "24.33.41.37"),
366 ("196.11.1.0", "196.11.30.255"),
367 ("192.247.1.0", "192.247.10.255"),
368 ("3ffe:4:5::", "3ffe:4:5::ffff") ]
370 for start, end in netblocks:
371 print "netblock %s - %s:" % (start, end)
372 blocks = netblock_to_cidr(start, end)