Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1 | # Copyright 2007 Google Inc. |
| 2 | # Licensed to PSF under a Contributor Agreement. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 3 | |
| 4 | """A fast, lightweight IPv4/IPv6 manipulation library in Python. |
| 5 | |
| 6 | This library is used to create/poke/manipulate IPv4 and IPv6 addresses |
| 7 | and networks. |
| 8 | |
| 9 | """ |
| 10 | |
| 11 | __version__ = '1.0' |
| 12 | |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 13 | |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 14 | import functools |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 15 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 16 | IPV4LENGTH = 32 |
| 17 | IPV6LENGTH = 128 |
| 18 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 19 | class AddressValueError(ValueError): |
| 20 | """A Value Error related to the address.""" |
| 21 | |
| 22 | |
| 23 | class NetmaskValueError(ValueError): |
| 24 | """A Value Error related to the netmask.""" |
| 25 | |
| 26 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 27 | def ip_address(address): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 28 | """Take an IP string/int and return an object of the correct type. |
| 29 | |
| 30 | Args: |
| 31 | address: A string or integer, the IP address. Either IPv4 or |
| 32 | IPv6 addresses may be supplied; integers less than 2**32 will |
| 33 | be considered to be IPv4 by default. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 34 | |
| 35 | Returns: |
| 36 | An IPv4Address or IPv6Address object. |
| 37 | |
| 38 | Raises: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 39 | ValueError: if the *address* passed isn't either a v4 or a v6 |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 40 | address |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 41 | |
| 42 | """ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 43 | try: |
| 44 | return IPv4Address(address) |
| 45 | except (AddressValueError, NetmaskValueError): |
| 46 | pass |
| 47 | |
| 48 | try: |
| 49 | return IPv6Address(address) |
| 50 | except (AddressValueError, NetmaskValueError): |
| 51 | pass |
| 52 | |
| 53 | raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % |
| 54 | address) |
| 55 | |
| 56 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 57 | def ip_network(address, strict=True): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 58 | """Take an IP string/int and return an object of the correct type. |
| 59 | |
| 60 | Args: |
| 61 | address: A string or integer, the IP network. Either IPv4 or |
| 62 | IPv6 networks may be supplied; integers less than 2**32 will |
| 63 | be considered to be IPv4 by default. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 64 | |
| 65 | Returns: |
| 66 | An IPv4Network or IPv6Network object. |
| 67 | |
| 68 | Raises: |
| 69 | ValueError: if the string passed isn't either a v4 or a v6 |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 70 | address. Or if the network has host bits set. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 71 | |
| 72 | """ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 73 | try: |
| 74 | return IPv4Network(address, strict) |
| 75 | except (AddressValueError, NetmaskValueError): |
| 76 | pass |
| 77 | |
| 78 | try: |
| 79 | return IPv6Network(address, strict) |
| 80 | except (AddressValueError, NetmaskValueError): |
| 81 | pass |
| 82 | |
| 83 | raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % |
| 84 | address) |
| 85 | |
| 86 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 87 | def ip_interface(address): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 88 | """Take an IP string/int and return an object of the correct type. |
| 89 | |
| 90 | Args: |
| 91 | address: A string or integer, the IP address. Either IPv4 or |
| 92 | IPv6 addresses may be supplied; integers less than 2**32 will |
| 93 | be considered to be IPv4 by default. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 94 | |
| 95 | Returns: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 96 | An IPv4Interface or IPv6Interface object. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 97 | |
| 98 | Raises: |
| 99 | ValueError: if the string passed isn't either a v4 or a v6 |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 100 | address. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 101 | |
| 102 | Notes: |
| 103 | The IPv?Interface classes describe an Address on a particular |
| 104 | Network, so they're basically a combination of both the Address |
| 105 | and Network classes. |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 106 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 107 | """ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 108 | try: |
| 109 | return IPv4Interface(address) |
| 110 | except (AddressValueError, NetmaskValueError): |
| 111 | pass |
| 112 | |
| 113 | try: |
| 114 | return IPv6Interface(address) |
| 115 | except (AddressValueError, NetmaskValueError): |
| 116 | pass |
| 117 | |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 118 | raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 119 | address) |
| 120 | |
| 121 | |
| 122 | def v4_int_to_packed(address): |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 123 | """Represent an address as 4 packed bytes in network (big-endian) order. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 124 | |
| 125 | Args: |
| 126 | address: An integer representation of an IPv4 IP address. |
| 127 | |
| 128 | Returns: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 129 | The integer address packed as 4 bytes in network (big-endian) order. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 130 | |
| 131 | Raises: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 132 | ValueError: If the integer is negative or too large to be an |
| 133 | IPv4 IP address. |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 134 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 135 | """ |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 136 | try: |
Nick Coghlan | db7920b | 2012-08-20 10:19:12 +1000 | [diff] [blame] | 137 | return address.to_bytes(4, 'big') |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 138 | except: |
| 139 | raise ValueError("Address negative or too large for IPv4") |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 140 | |
| 141 | |
| 142 | def v6_int_to_packed(address): |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 143 | """Represent an address as 16 packed bytes in network (big-endian) order. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 144 | |
| 145 | Args: |
Sandro Tosi | b4386d3 | 2012-06-02 17:14:22 +0200 | [diff] [blame] | 146 | address: An integer representation of an IPv6 IP address. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 147 | |
| 148 | Returns: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 149 | The integer address packed as 16 bytes in network (big-endian) order. |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 150 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 151 | """ |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 152 | try: |
Nick Coghlan | db7920b | 2012-08-20 10:19:12 +1000 | [diff] [blame] | 153 | return address.to_bytes(16, 'big') |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 154 | except: |
| 155 | raise ValueError("Address negative or too large for IPv6") |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 156 | |
| 157 | |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 158 | def _split_optional_netmask(address): |
| 159 | """Helper to split the netmask and raise AddressValueError if needed""" |
| 160 | addr = str(address).split('/') |
| 161 | if len(addr) > 2: |
| 162 | raise AddressValueError("Only one '/' permitted in %r" % address) |
| 163 | return addr |
| 164 | |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 165 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 166 | def _find_address_range(addresses): |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 167 | """Find a sequence of IPv#Address. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 168 | |
| 169 | Args: |
Sandro Tosi | 876ecad | 2012-05-23 22:26:55 +0200 | [diff] [blame] | 170 | addresses: a list of IPv#Address objects. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 171 | |
| 172 | Returns: |
| 173 | A tuple containing the first and last IP addresses in the sequence. |
| 174 | |
| 175 | """ |
| 176 | first = last = addresses[0] |
| 177 | for ip in addresses[1:]: |
| 178 | if ip._ip == last._ip + 1: |
| 179 | last = ip |
| 180 | else: |
| 181 | break |
| 182 | return (first, last) |
| 183 | |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 184 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 185 | def _count_righthand_zero_bits(number, bits): |
| 186 | """Count the number of zero bits on the right hand side. |
| 187 | |
| 188 | Args: |
| 189 | number: an integer. |
| 190 | bits: maximum number of bits to count. |
| 191 | |
| 192 | Returns: |
| 193 | The number of zero bits on the right hand side of the number. |
| 194 | |
| 195 | """ |
| 196 | if number == 0: |
| 197 | return bits |
| 198 | for i in range(bits): |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 199 | if (number >> i) & 1: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 200 | return i |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 201 | # All bits of interest were zero, even if there are more in the number |
| 202 | return bits |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 203 | |
| 204 | |
| 205 | def summarize_address_range(first, last): |
| 206 | """Summarize a network range given the first and last IP addresses. |
| 207 | |
| 208 | Example: |
| 209 | >>> summarize_address_range(IPv4Address('192.0.2.0'), |
| 210 | IPv4Address('192.0.2.130')) |
| 211 | [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), |
| 212 | IPv4Network('192.0.2.130/32')] |
| 213 | |
| 214 | Args: |
| 215 | first: the first IPv4Address or IPv6Address in the range. |
| 216 | last: the last IPv4Address or IPv6Address in the range. |
| 217 | |
| 218 | Returns: |
| 219 | An iterator of the summarized IPv(4|6) network objects. |
| 220 | |
| 221 | Raise: |
| 222 | TypeError: |
| 223 | If the first and last objects are not IP addresses. |
| 224 | If the first and last objects are not the same version. |
| 225 | ValueError: |
| 226 | If the last object is not greater than the first. |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 227 | If the version of the first address is not 4 or 6. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 228 | |
| 229 | """ |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 230 | if (not (isinstance(first, _BaseAddress) and |
| 231 | isinstance(last, _BaseAddress))): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 232 | raise TypeError('first and last must be IP addresses, not networks') |
| 233 | if first.version != last.version: |
| 234 | raise TypeError("%s and %s are not of the same version" % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 235 | first, last)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 236 | if first > last: |
| 237 | raise ValueError('last IP address must be greater than first') |
| 238 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 239 | if first.version == 4: |
| 240 | ip = IPv4Network |
| 241 | elif first.version == 6: |
| 242 | ip = IPv6Network |
| 243 | else: |
| 244 | raise ValueError('unknown IP version') |
| 245 | |
| 246 | ip_bits = first._max_prefixlen |
| 247 | first_int = first._ip |
| 248 | last_int = last._ip |
| 249 | while first_int <= last_int: |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 250 | nbits = min(_count_righthand_zero_bits(first_int, ip_bits), |
| 251 | (last_int - first_int + 1).bit_length() - 1) |
| 252 | net = ip('%s/%d' % (first, ip_bits - nbits)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 253 | yield net |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 254 | first_int += 1 << nbits |
| 255 | if first_int - 1 == ip._ALL_ONES: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 256 | break |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 257 | first = first.__class__(first_int) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 258 | |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 259 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 260 | def _collapse_addresses_recursive(addresses): |
| 261 | """Loops through the addresses, collapsing concurrent netblocks. |
| 262 | |
| 263 | Example: |
| 264 | |
| 265 | ip1 = IPv4Network('192.0.2.0/26') |
| 266 | ip2 = IPv4Network('192.0.2.64/26') |
| 267 | ip3 = IPv4Network('192.0.2.128/26') |
| 268 | ip4 = IPv4Network('192.0.2.192/26') |
| 269 | |
| 270 | _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> |
| 271 | [IPv4Network('192.0.2.0/24')] |
| 272 | |
| 273 | This shouldn't be called directly; it is called via |
| 274 | collapse_addresses([]). |
| 275 | |
| 276 | Args: |
| 277 | addresses: A list of IPv4Network's or IPv6Network's |
| 278 | |
| 279 | Returns: |
| 280 | A list of IPv4Network's or IPv6Network's depending on what we were |
| 281 | passed. |
| 282 | |
| 283 | """ |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 284 | while True: |
| 285 | last_addr = None |
| 286 | ret_array = [] |
| 287 | optimized = False |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 288 | |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 289 | for cur_addr in addresses: |
| 290 | if not ret_array: |
| 291 | last_addr = cur_addr |
| 292 | ret_array.append(cur_addr) |
| 293 | elif (cur_addr.network_address >= last_addr.network_address and |
| 294 | cur_addr.broadcast_address <= last_addr.broadcast_address): |
| 295 | optimized = True |
| 296 | elif cur_addr == list(last_addr.supernet().subnets())[1]: |
| 297 | ret_array[-1] = last_addr = last_addr.supernet() |
| 298 | optimized = True |
| 299 | else: |
| 300 | last_addr = cur_addr |
| 301 | ret_array.append(cur_addr) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 302 | |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 303 | addresses = ret_array |
| 304 | if not optimized: |
| 305 | return addresses |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 306 | |
| 307 | |
| 308 | def collapse_addresses(addresses): |
| 309 | """Collapse a list of IP objects. |
| 310 | |
| 311 | Example: |
| 312 | collapse_addresses([IPv4Network('192.0.2.0/25'), |
| 313 | IPv4Network('192.0.2.128/25')]) -> |
| 314 | [IPv4Network('192.0.2.0/24')] |
| 315 | |
| 316 | Args: |
| 317 | addresses: An iterator of IPv4Network or IPv6Network objects. |
| 318 | |
| 319 | Returns: |
| 320 | An iterator of the collapsed IPv(4|6)Network objects. |
| 321 | |
| 322 | Raises: |
| 323 | TypeError: If passed a list of mixed version objects. |
| 324 | |
| 325 | """ |
| 326 | i = 0 |
| 327 | addrs = [] |
| 328 | ips = [] |
| 329 | nets = [] |
| 330 | |
| 331 | # split IP addresses and networks |
| 332 | for ip in addresses: |
| 333 | if isinstance(ip, _BaseAddress): |
| 334 | if ips and ips[-1]._version != ip._version: |
| 335 | raise TypeError("%s and %s are not of the same version" % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 336 | ip, ips[-1])) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 337 | ips.append(ip) |
| 338 | elif ip._prefixlen == ip._max_prefixlen: |
| 339 | if ips and ips[-1]._version != ip._version: |
| 340 | raise TypeError("%s and %s are not of the same version" % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 341 | ip, ips[-1])) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 342 | try: |
| 343 | ips.append(ip.ip) |
| 344 | except AttributeError: |
| 345 | ips.append(ip.network_address) |
| 346 | else: |
| 347 | if nets and nets[-1]._version != ip._version: |
| 348 | raise TypeError("%s and %s are not of the same version" % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 349 | ip, nets[-1])) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 350 | nets.append(ip) |
| 351 | |
| 352 | # sort and dedup |
| 353 | ips = sorted(set(ips)) |
| 354 | nets = sorted(set(nets)) |
| 355 | |
| 356 | while i < len(ips): |
| 357 | (first, last) = _find_address_range(ips[i:]) |
| 358 | i = ips.index(last) + 1 |
| 359 | addrs.extend(summarize_address_range(first, last)) |
| 360 | |
| 361 | return iter(_collapse_addresses_recursive(sorted( |
| 362 | addrs + nets, key=_BaseNetwork._get_networks_key))) |
| 363 | |
| 364 | |
| 365 | def get_mixed_type_key(obj): |
| 366 | """Return a key suitable for sorting between networks and addresses. |
| 367 | |
| 368 | Address and Network objects are not sortable by default; they're |
| 369 | fundamentally different so the expression |
| 370 | |
| 371 | IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') |
| 372 | |
| 373 | doesn't make any sense. There are some times however, where you may wish |
| 374 | to have ipaddress sort these for you anyway. If you need to do this, you |
| 375 | can use this function as the key= argument to sorted(). |
| 376 | |
| 377 | Args: |
| 378 | obj: either a Network or Address object. |
| 379 | Returns: |
| 380 | appropriate key. |
| 381 | |
| 382 | """ |
| 383 | if isinstance(obj, _BaseNetwork): |
| 384 | return obj._get_networks_key() |
| 385 | elif isinstance(obj, _BaseAddress): |
| 386 | return obj._get_address_key() |
| 387 | return NotImplemented |
| 388 | |
| 389 | |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 390 | class _TotalOrderingMixin: |
| 391 | # Helper that derives the other comparison operations from |
| 392 | # __lt__ and __eq__ |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 393 | # We avoid functools.total_ordering because it doesn't handle |
| 394 | # NotImplemented correctly yet (http://bugs.python.org/issue10042) |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 395 | def __eq__(self, other): |
| 396 | raise NotImplementedError |
| 397 | def __ne__(self, other): |
| 398 | equal = self.__eq__(other) |
| 399 | if equal is NotImplemented: |
| 400 | return NotImplemented |
| 401 | return not equal |
| 402 | def __lt__(self, other): |
| 403 | raise NotImplementedError |
| 404 | def __le__(self, other): |
| 405 | less = self.__lt__(other) |
| 406 | if less is NotImplemented or not less: |
| 407 | return self.__eq__(other) |
| 408 | return less |
| 409 | def __gt__(self, other): |
| 410 | less = self.__lt__(other) |
| 411 | if less is NotImplemented: |
| 412 | return NotImplemented |
| 413 | equal = self.__eq__(other) |
| 414 | if equal is NotImplemented: |
| 415 | return NotImplemented |
| 416 | return not (less or equal) |
| 417 | def __ge__(self, other): |
| 418 | less = self.__lt__(other) |
| 419 | if less is NotImplemented: |
| 420 | return NotImplemented |
| 421 | return not less |
| 422 | |
| 423 | class _IPAddressBase(_TotalOrderingMixin): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 424 | |
| 425 | """The mother class.""" |
| 426 | |
| 427 | @property |
| 428 | def exploded(self): |
| 429 | """Return the longhand version of the IP address as a string.""" |
| 430 | return self._explode_shorthand_ip_string() |
| 431 | |
| 432 | @property |
| 433 | def compressed(self): |
| 434 | """Return the shorthand version of the IP address as a string.""" |
| 435 | return str(self) |
| 436 | |
Nick Coghlan | d972265 | 2012-06-17 16:33:00 +1000 | [diff] [blame] | 437 | @property |
| 438 | def version(self): |
| 439 | msg = '%200s has no version specified' % (type(self),) |
| 440 | raise NotImplementedError(msg) |
| 441 | |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 442 | def _check_int_address(self, address): |
| 443 | if address < 0: |
| 444 | msg = "%d (< 0) is not permitted as an IPv%d address" |
| 445 | raise AddressValueError(msg % (address, self._version)) |
| 446 | if address > self._ALL_ONES: |
| 447 | msg = "%d (>= 2**%d) is not permitted as an IPv%d address" |
| 448 | raise AddressValueError(msg % (address, self._max_prefixlen, |
| 449 | self._version)) |
| 450 | |
| 451 | def _check_packed_address(self, address, expected_len): |
| 452 | address_len = len(address) |
| 453 | if address_len != expected_len: |
| 454 | msg = "%r (len %d != %d) is not permitted as an IPv%d address" |
| 455 | raise AddressValueError(msg % (address, address_len, |
| 456 | expected_len, self._version)) |
| 457 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 458 | def _ip_int_from_prefix(self, prefixlen=None): |
| 459 | """Turn the prefix length netmask into a int for comparison. |
| 460 | |
| 461 | Args: |
| 462 | prefixlen: An integer, the prefix length. |
| 463 | |
| 464 | Returns: |
| 465 | An integer. |
| 466 | |
| 467 | """ |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 468 | if prefixlen is None: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 469 | prefixlen = self._prefixlen |
| 470 | return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) |
| 471 | |
| 472 | def _prefix_from_ip_int(self, ip_int, mask=32): |
| 473 | """Return prefix length from the decimal netmask. |
| 474 | |
| 475 | Args: |
| 476 | ip_int: An integer, the IP address. |
| 477 | mask: The netmask. Defaults to 32. |
| 478 | |
| 479 | Returns: |
| 480 | An integer, the prefix length. |
| 481 | |
| 482 | """ |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 483 | return mask - _count_righthand_zero_bits(ip_int, mask) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 484 | |
| 485 | def _ip_string_from_prefix(self, prefixlen=None): |
| 486 | """Turn a prefix length into a dotted decimal string. |
| 487 | |
| 488 | Args: |
| 489 | prefixlen: An integer, the netmask prefix length. |
| 490 | |
| 491 | Returns: |
| 492 | A string, the dotted decimal netmask string. |
| 493 | |
| 494 | """ |
| 495 | if not prefixlen: |
| 496 | prefixlen = self._prefixlen |
| 497 | return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen)) |
| 498 | |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 499 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 500 | class _BaseAddress(_IPAddressBase): |
| 501 | |
| 502 | """A generic IP object. |
| 503 | |
| 504 | This IP class contains the version independent methods which are |
| 505 | used by single IP addresses. |
| 506 | |
| 507 | """ |
| 508 | |
| 509 | def __init__(self, address): |
| 510 | if (not isinstance(address, bytes) |
| 511 | and '/' in str(address)): |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 512 | raise AddressValueError("Unexpected '/' in %r" % address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 513 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 514 | def __int__(self): |
| 515 | return self._ip |
| 516 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 517 | def __eq__(self, other): |
| 518 | try: |
| 519 | return (self._ip == other._ip |
| 520 | and self._version == other._version) |
| 521 | except AttributeError: |
| 522 | return NotImplemented |
| 523 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 524 | def __lt__(self, other): |
| 525 | if self._version != other._version: |
| 526 | raise TypeError('%s and %s are not of the same version' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 527 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 528 | if not isinstance(other, _BaseAddress): |
| 529 | raise TypeError('%s and %s are not of the same type' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 530 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 531 | if self._ip != other._ip: |
| 532 | return self._ip < other._ip |
| 533 | return False |
| 534 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 535 | # Shorthand for Integer addition and subtraction. This is not |
| 536 | # meant to ever support addition/subtraction of addresses. |
| 537 | def __add__(self, other): |
| 538 | if not isinstance(other, int): |
| 539 | return NotImplemented |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 540 | return self.__class__(int(self) + other) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 541 | |
| 542 | def __sub__(self, other): |
| 543 | if not isinstance(other, int): |
| 544 | return NotImplemented |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 545 | return self.__class__(int(self) - other) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 546 | |
| 547 | def __repr__(self): |
| 548 | return '%s(%r)' % (self.__class__.__name__, str(self)) |
| 549 | |
| 550 | def __str__(self): |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 551 | return str(self._string_from_ip_int(self._ip)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 552 | |
| 553 | def __hash__(self): |
| 554 | return hash(hex(int(self._ip))) |
| 555 | |
| 556 | def _get_address_key(self): |
| 557 | return (self._version, self) |
| 558 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 559 | |
| 560 | class _BaseNetwork(_IPAddressBase): |
| 561 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 562 | """A generic IP network object. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 563 | |
| 564 | This IP class contains the version independent methods which are |
| 565 | used by networks. |
| 566 | |
| 567 | """ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 568 | def __init__(self, address): |
| 569 | self._cache = {} |
| 570 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 571 | def __repr__(self): |
| 572 | return '%s(%r)' % (self.__class__.__name__, str(self)) |
| 573 | |
Hynek Schlawack | 454a74d | 2012-06-04 18:14:02 +0200 | [diff] [blame] | 574 | def __str__(self): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 575 | return '%s/%d' % (self.network_address, self.prefixlen) |
Hynek Schlawack | 454a74d | 2012-06-04 18:14:02 +0200 | [diff] [blame] | 576 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 577 | def hosts(self): |
| 578 | """Generate Iterator over usable hosts in a network. |
| 579 | |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 580 | This is like __iter__ except it doesn't return the network |
| 581 | or broadcast addresses. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 582 | |
| 583 | """ |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 584 | network = int(self.network_address) |
| 585 | broadcast = int(self.broadcast_address) |
| 586 | for x in range(network + 1, broadcast): |
| 587 | yield self._address_class(x) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 588 | |
| 589 | def __iter__(self): |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 590 | network = int(self.network_address) |
| 591 | broadcast = int(self.broadcast_address) |
| 592 | for x in range(network, broadcast + 1): |
| 593 | yield self._address_class(x) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 594 | |
| 595 | def __getitem__(self, n): |
| 596 | network = int(self.network_address) |
| 597 | broadcast = int(self.broadcast_address) |
| 598 | if n >= 0: |
| 599 | if network + n > broadcast: |
| 600 | raise IndexError |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 601 | return self._address_class(network + n) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 602 | else: |
| 603 | n += 1 |
| 604 | if broadcast + n < network: |
| 605 | raise IndexError |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 606 | return self._address_class(broadcast + n) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 607 | |
| 608 | def __lt__(self, other): |
| 609 | if self._version != other._version: |
| 610 | raise TypeError('%s and %s are not of the same version' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 611 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 612 | if not isinstance(other, _BaseNetwork): |
| 613 | raise TypeError('%s and %s are not of the same type' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 614 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 615 | if self.network_address != other.network_address: |
| 616 | return self.network_address < other.network_address |
| 617 | if self.netmask != other.netmask: |
| 618 | return self.netmask < other.netmask |
| 619 | return False |
| 620 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 621 | def __eq__(self, other): |
Nick Coghlan | 9a9c28c | 2012-07-07 23:05:59 +1000 | [diff] [blame] | 622 | try: |
| 623 | return (self._version == other._version and |
| 624 | self.network_address == other.network_address and |
| 625 | int(self.netmask) == int(other.netmask)) |
| 626 | except AttributeError: |
| 627 | return NotImplemented |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 628 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 629 | def __hash__(self): |
| 630 | return hash(int(self.network_address) ^ int(self.netmask)) |
| 631 | |
| 632 | def __contains__(self, other): |
| 633 | # always false if one is v4 and the other is v6. |
| 634 | if self._version != other._version: |
| 635 | return False |
| 636 | # dealing with another network. |
| 637 | if isinstance(other, _BaseNetwork): |
| 638 | return False |
| 639 | # dealing with another address |
| 640 | else: |
| 641 | # address |
| 642 | return (int(self.network_address) <= int(other._ip) <= |
| 643 | int(self.broadcast_address)) |
| 644 | |
| 645 | def overlaps(self, other): |
| 646 | """Tell if self is partly contained in other.""" |
| 647 | return self.network_address in other or ( |
| 648 | self.broadcast_address in other or ( |
| 649 | other.network_address in self or ( |
| 650 | other.broadcast_address in self))) |
| 651 | |
| 652 | @property |
| 653 | def broadcast_address(self): |
| 654 | x = self._cache.get('broadcast_address') |
| 655 | if x is None: |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 656 | x = self._address_class(int(self.network_address) | |
| 657 | int(self.hostmask)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 658 | self._cache['broadcast_address'] = x |
| 659 | return x |
| 660 | |
| 661 | @property |
| 662 | def hostmask(self): |
| 663 | x = self._cache.get('hostmask') |
| 664 | if x is None: |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 665 | x = self._address_class(int(self.netmask) ^ self._ALL_ONES) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 666 | self._cache['hostmask'] = x |
| 667 | return x |
| 668 | |
| 669 | @property |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 670 | def with_prefixlen(self): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 671 | return '%s/%d' % (self.network_address, self._prefixlen) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 672 | |
| 673 | @property |
| 674 | def with_netmask(self): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 675 | return '%s/%s' % (self.network_address, self.netmask) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 676 | |
| 677 | @property |
| 678 | def with_hostmask(self): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 679 | return '%s/%s' % (self.network_address, self.hostmask) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 680 | |
| 681 | @property |
| 682 | def num_addresses(self): |
| 683 | """Number of hosts in the current subnet.""" |
| 684 | return int(self.broadcast_address) - int(self.network_address) + 1 |
| 685 | |
| 686 | @property |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 687 | def _address_class(self): |
Nick Coghlan | d972265 | 2012-06-17 16:33:00 +1000 | [diff] [blame] | 688 | # Returning bare address objects (rather than interfaces) allows for |
| 689 | # more consistent behaviour across the network address, broadcast |
| 690 | # address and individual host addresses. |
| 691 | msg = '%200s has no associated address class' % (type(self),) |
| 692 | raise NotImplementedError(msg) |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 693 | |
| 694 | @property |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 695 | def prefixlen(self): |
| 696 | return self._prefixlen |
| 697 | |
| 698 | def address_exclude(self, other): |
| 699 | """Remove an address from a larger block. |
| 700 | |
| 701 | For example: |
| 702 | |
| 703 | addr1 = ip_network('192.0.2.0/28') |
| 704 | addr2 = ip_network('192.0.2.1/32') |
| 705 | addr1.address_exclude(addr2) = |
| 706 | [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), |
| 707 | IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] |
| 708 | |
| 709 | or IPv6: |
| 710 | |
| 711 | addr1 = ip_network('2001:db8::1/32') |
| 712 | addr2 = ip_network('2001:db8::1/128') |
| 713 | addr1.address_exclude(addr2) = |
| 714 | [ip_network('2001:db8::1/128'), |
| 715 | ip_network('2001:db8::2/127'), |
| 716 | ip_network('2001:db8::4/126'), |
| 717 | ip_network('2001:db8::8/125'), |
| 718 | ... |
| 719 | ip_network('2001:db8:8000::/33')] |
| 720 | |
| 721 | Args: |
| 722 | other: An IPv4Network or IPv6Network object of the same type. |
| 723 | |
| 724 | Returns: |
| 725 | An iterator of the the IPv(4|6)Network objects which is self |
| 726 | minus other. |
| 727 | |
| 728 | Raises: |
| 729 | TypeError: If self and other are of difffering address |
| 730 | versions, or if other is not a network object. |
| 731 | ValueError: If other is not completely contained by self. |
| 732 | |
| 733 | """ |
| 734 | if not self._version == other._version: |
| 735 | raise TypeError("%s and %s are not of the same version" % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 736 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 737 | |
| 738 | if not isinstance(other, _BaseNetwork): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 739 | raise TypeError("%s is not a network object" % other) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 740 | |
| 741 | if not (other.network_address >= self.network_address and |
| 742 | other.broadcast_address <= self.broadcast_address): |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 743 | raise ValueError('%s not contained in %s' % (other, self)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 744 | if other == self: |
| 745 | raise StopIteration |
| 746 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 747 | # Make sure we're comparing the network of other. |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 748 | other = other.__class__('%s/%s' % (other.network_address, |
| 749 | other.prefixlen)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 750 | |
| 751 | s1, s2 = self.subnets() |
| 752 | while s1 != other and s2 != other: |
| 753 | if (other.network_address >= s1.network_address and |
| 754 | other.broadcast_address <= s1.broadcast_address): |
| 755 | yield s2 |
| 756 | s1, s2 = s1.subnets() |
| 757 | elif (other.network_address >= s2.network_address and |
| 758 | other.broadcast_address <= s2.broadcast_address): |
| 759 | yield s1 |
| 760 | s1, s2 = s2.subnets() |
| 761 | else: |
| 762 | # If we got here, there's a bug somewhere. |
| 763 | raise AssertionError('Error performing exclusion: ' |
| 764 | 's1: %s s2: %s other: %s' % |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 765 | (s1, s2, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 766 | if s1 == other: |
| 767 | yield s2 |
| 768 | elif s2 == other: |
| 769 | yield s1 |
| 770 | else: |
| 771 | # If we got here, there's a bug somewhere. |
| 772 | raise AssertionError('Error performing exclusion: ' |
| 773 | 's1: %s s2: %s other: %s' % |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 774 | (s1, s2, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 775 | |
| 776 | def compare_networks(self, other): |
| 777 | """Compare two IP objects. |
| 778 | |
| 779 | This is only concerned about the comparison of the integer |
| 780 | representation of the network addresses. This means that the |
| 781 | host bits aren't considered at all in this method. If you want |
| 782 | to compare host bits, you can easily enough do a |
| 783 | 'HostA._ip < HostB._ip' |
| 784 | |
| 785 | Args: |
| 786 | other: An IP object. |
| 787 | |
| 788 | Returns: |
| 789 | If the IP versions of self and other are the same, returns: |
| 790 | |
| 791 | -1 if self < other: |
| 792 | eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') |
| 793 | IPv6Network('2001:db8::1000/124') < |
| 794 | IPv6Network('2001:db8::2000/124') |
| 795 | 0 if self == other |
| 796 | eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') |
| 797 | IPv6Network('2001:db8::1000/124') == |
| 798 | IPv6Network('2001:db8::1000/124') |
| 799 | 1 if self > other |
| 800 | eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') |
| 801 | IPv6Network('2001:db8::2000/124') > |
| 802 | IPv6Network('2001:db8::1000/124') |
| 803 | |
| 804 | Raises: |
| 805 | TypeError if the IP versions are different. |
| 806 | |
| 807 | """ |
| 808 | # does this need to raise a ValueError? |
| 809 | if self._version != other._version: |
| 810 | raise TypeError('%s and %s are not of the same type' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 811 | self, other)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 812 | # self._version == other._version below here: |
| 813 | if self.network_address < other.network_address: |
| 814 | return -1 |
| 815 | if self.network_address > other.network_address: |
| 816 | return 1 |
| 817 | # self.network_address == other.network_address below here: |
| 818 | if self.netmask < other.netmask: |
| 819 | return -1 |
| 820 | if self.netmask > other.netmask: |
| 821 | return 1 |
| 822 | return 0 |
| 823 | |
| 824 | def _get_networks_key(self): |
| 825 | """Network-only key function. |
| 826 | |
| 827 | Returns an object that identifies this address' network and |
| 828 | netmask. This function is a suitable "key" argument for sorted() |
| 829 | and list.sort(). |
| 830 | |
| 831 | """ |
| 832 | return (self._version, self.network_address, self.netmask) |
| 833 | |
| 834 | def subnets(self, prefixlen_diff=1, new_prefix=None): |
| 835 | """The subnets which join to make the current subnet. |
| 836 | |
| 837 | In the case that self contains only one IP |
| 838 | (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 |
| 839 | for IPv6), yield an iterator with just ourself. |
| 840 | |
| 841 | Args: |
| 842 | prefixlen_diff: An integer, the amount the prefix length |
| 843 | should be increased by. This should not be set if |
| 844 | new_prefix is also set. |
| 845 | new_prefix: The desired new prefix length. This must be a |
| 846 | larger number (smaller prefix) than the existing prefix. |
| 847 | This should not be set if prefixlen_diff is also set. |
| 848 | |
| 849 | Returns: |
| 850 | An iterator of IPv(4|6) objects. |
| 851 | |
| 852 | Raises: |
| 853 | ValueError: The prefixlen_diff is too small or too large. |
| 854 | OR |
| 855 | prefixlen_diff and new_prefix are both set or new_prefix |
| 856 | is a smaller number than the current prefix (smaller |
| 857 | number means a larger network) |
| 858 | |
| 859 | """ |
| 860 | if self._prefixlen == self._max_prefixlen: |
| 861 | yield self |
| 862 | return |
| 863 | |
| 864 | if new_prefix is not None: |
| 865 | if new_prefix < self._prefixlen: |
| 866 | raise ValueError('new prefix must be longer') |
| 867 | if prefixlen_diff != 1: |
| 868 | raise ValueError('cannot set prefixlen_diff and new_prefix') |
| 869 | prefixlen_diff = new_prefix - self._prefixlen |
| 870 | |
| 871 | if prefixlen_diff < 0: |
| 872 | raise ValueError('prefix length diff must be > 0') |
| 873 | new_prefixlen = self._prefixlen + prefixlen_diff |
| 874 | |
| 875 | if not self._is_valid_netmask(str(new_prefixlen)): |
| 876 | raise ValueError( |
| 877 | 'prefix length diff %d is invalid for netblock %s' % ( |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 878 | new_prefixlen, self)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 879 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 880 | first = self.__class__('%s/%s' % |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 881 | (self.network_address, |
| 882 | self._prefixlen + prefixlen_diff)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 883 | |
| 884 | yield first |
| 885 | current = first |
| 886 | while True: |
| 887 | broadcast = current.broadcast_address |
| 888 | if broadcast == self.broadcast_address: |
| 889 | return |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 890 | new_addr = self._address_class(int(broadcast) + 1) |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 891 | current = self.__class__('%s/%s' % (new_addr, |
| 892 | new_prefixlen)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 893 | |
| 894 | yield current |
| 895 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 896 | def supernet(self, prefixlen_diff=1, new_prefix=None): |
| 897 | """The supernet containing the current network. |
| 898 | |
| 899 | Args: |
| 900 | prefixlen_diff: An integer, the amount the prefix length of |
| 901 | the network should be decreased by. For example, given a |
| 902 | /24 network and a prefixlen_diff of 3, a supernet with a |
| 903 | /21 netmask is returned. |
| 904 | |
| 905 | Returns: |
| 906 | An IPv4 network object. |
| 907 | |
| 908 | Raises: |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 909 | ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have |
| 910 | a negative prefix length. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 911 | OR |
| 912 | If prefixlen_diff and new_prefix are both set or new_prefix is a |
| 913 | larger number than the current prefix (larger number means a |
| 914 | smaller network) |
| 915 | |
| 916 | """ |
| 917 | if self._prefixlen == 0: |
| 918 | return self |
| 919 | |
| 920 | if new_prefix is not None: |
| 921 | if new_prefix > self._prefixlen: |
| 922 | raise ValueError('new prefix must be shorter') |
| 923 | if prefixlen_diff != 1: |
| 924 | raise ValueError('cannot set prefixlen_diff and new_prefix') |
| 925 | prefixlen_diff = self._prefixlen - new_prefix |
| 926 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 927 | if self.prefixlen - prefixlen_diff < 0: |
| 928 | raise ValueError( |
| 929 | 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % |
| 930 | (self.prefixlen, prefixlen_diff)) |
| 931 | # TODO (pmoody): optimize this. |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 932 | t = self.__class__('%s/%d' % (self.network_address, |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 933 | self.prefixlen - prefixlen_diff), |
| 934 | strict=False) |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 935 | return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 936 | |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 937 | @property |
| 938 | def is_multicast(self): |
| 939 | """Test if the address is reserved for multicast use. |
| 940 | |
| 941 | Returns: |
| 942 | A boolean, True if the address is a multicast address. |
| 943 | See RFC 2373 2.7 for details. |
| 944 | |
| 945 | """ |
| 946 | return (self.network_address.is_multicast and |
| 947 | self.broadcast_address.is_multicast) |
| 948 | |
| 949 | @property |
| 950 | def is_reserved(self): |
| 951 | """Test if the address is otherwise IETF reserved. |
| 952 | |
| 953 | Returns: |
| 954 | A boolean, True if the address is within one of the |
| 955 | reserved IPv6 Network ranges. |
| 956 | |
| 957 | """ |
| 958 | return (self.network_address.is_reserved and |
| 959 | self.broadcast_address.is_reserved) |
| 960 | |
| 961 | @property |
| 962 | def is_link_local(self): |
| 963 | """Test if the address is reserved for link-local. |
| 964 | |
| 965 | Returns: |
| 966 | A boolean, True if the address is reserved per RFC 4291. |
| 967 | |
| 968 | """ |
| 969 | return (self.network_address.is_link_local and |
| 970 | self.broadcast_address.is_link_local) |
| 971 | |
| 972 | @property |
| 973 | def is_private(self): |
| 974 | """Test if this address is allocated for private networks. |
| 975 | |
| 976 | Returns: |
| 977 | A boolean, True if the address is reserved per RFC 4193. |
| 978 | |
| 979 | """ |
| 980 | return (self.network_address.is_private and |
| 981 | self.broadcast_address.is_private) |
| 982 | |
| 983 | @property |
| 984 | def is_unspecified(self): |
| 985 | """Test if the address is unspecified. |
| 986 | |
| 987 | Returns: |
| 988 | A boolean, True if this is the unspecified address as defined in |
| 989 | RFC 2373 2.5.2. |
| 990 | |
| 991 | """ |
| 992 | return (self.network_address.is_unspecified and |
| 993 | self.broadcast_address.is_unspecified) |
| 994 | |
| 995 | @property |
| 996 | def is_loopback(self): |
| 997 | """Test if the address is a loopback address. |
| 998 | |
| 999 | Returns: |
| 1000 | A boolean, True if the address is a loopback address as defined in |
| 1001 | RFC 2373 2.5.3. |
| 1002 | |
| 1003 | """ |
| 1004 | return (self.network_address.is_loopback and |
| 1005 | self.broadcast_address.is_loopback) |
| 1006 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1007 | |
Hynek Schlawack | c4b78a3 | 2012-06-01 11:48:32 +0200 | [diff] [blame] | 1008 | class _BaseV4: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1009 | |
| 1010 | """Base IPv4 object. |
| 1011 | |
| 1012 | The following methods are used by IPv4 objects in both single IP |
| 1013 | addresses and networks. |
| 1014 | |
| 1015 | """ |
| 1016 | |
| 1017 | # Equivalent to 255.255.255.255 or 32 bits of 1's. |
| 1018 | _ALL_ONES = (2**IPV4LENGTH) - 1 |
| 1019 | _DECIMAL_DIGITS = frozenset('0123456789') |
| 1020 | |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1021 | # the valid octets for host and netmasks. only useful for IPv4. |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1022 | _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1023 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1024 | def __init__(self, address): |
| 1025 | self._version = 4 |
| 1026 | self._max_prefixlen = IPV4LENGTH |
| 1027 | |
| 1028 | def _explode_shorthand_ip_string(self): |
| 1029 | return str(self) |
| 1030 | |
| 1031 | def _ip_int_from_string(self, ip_str): |
| 1032 | """Turn the given IP string into an integer for comparison. |
| 1033 | |
| 1034 | Args: |
| 1035 | ip_str: A string, the IP ip_str. |
| 1036 | |
| 1037 | Returns: |
| 1038 | The IP ip_str as an integer. |
| 1039 | |
| 1040 | Raises: |
| 1041 | AddressValueError: if ip_str isn't a valid IPv4 Address. |
| 1042 | |
| 1043 | """ |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1044 | if not ip_str: |
| 1045 | raise AddressValueError('Address cannot be empty') |
| 1046 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1047 | octets = ip_str.split('.') |
| 1048 | if len(octets) != 4: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1049 | raise AddressValueError("Expected 4 octets in %r" % ip_str) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1050 | |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1051 | try: |
| 1052 | return int.from_bytes(map(self._parse_octet, octets), 'big') |
| 1053 | except ValueError as exc: |
| 1054 | raise AddressValueError("%s in %r" % (exc, ip_str)) from None |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1055 | |
| 1056 | def _parse_octet(self, octet_str): |
| 1057 | """Convert a decimal octet into an integer. |
| 1058 | |
| 1059 | Args: |
| 1060 | octet_str: A string, the number to parse. |
| 1061 | |
| 1062 | Returns: |
| 1063 | The octet as an integer. |
| 1064 | |
| 1065 | Raises: |
| 1066 | ValueError: if the octet isn't strictly a decimal from [0..255]. |
| 1067 | |
| 1068 | """ |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1069 | if not octet_str: |
| 1070 | raise ValueError("Empty octet not permitted") |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1071 | # Whitelist the characters, since int() allows a lot of bizarre stuff. |
| 1072 | if not self._DECIMAL_DIGITS.issuperset(octet_str): |
Nick Coghlan | 07c4e33 | 2012-07-08 23:06:45 +1000 | [diff] [blame] | 1073 | msg = "Only decimal digits permitted in %r" |
| 1074 | raise ValueError(msg % octet_str) |
| 1075 | # We do the length check second, since the invalid character error |
| 1076 | # is likely to be more informative for the user |
| 1077 | if len(octet_str) > 3: |
| 1078 | msg = "At most 3 characters permitted in %r" |
| 1079 | raise ValueError(msg % octet_str) |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1080 | # Convert to integer (we know digits are legal) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1081 | octet_int = int(octet_str, 10) |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1082 | # Any octets that look like they *might* be written in octal, |
| 1083 | # and which don't look exactly the same in both octal and |
| 1084 | # decimal are rejected as ambiguous |
| 1085 | if octet_int > 7 and octet_str[0] == '0': |
Nick Coghlan | 07c4e33 | 2012-07-08 23:06:45 +1000 | [diff] [blame] | 1086 | msg = "Ambiguous (octal/decimal) value in %r not permitted" |
| 1087 | raise ValueError(msg % octet_str) |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1088 | if octet_int > 255: |
Nick Coghlan | b582ecc | 2012-07-07 22:15:22 +1000 | [diff] [blame] | 1089 | raise ValueError("Octet %d (> 255) not permitted" % octet_int) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1090 | return octet_int |
| 1091 | |
| 1092 | def _string_from_ip_int(self, ip_int): |
| 1093 | """Turns a 32-bit integer into dotted decimal notation. |
| 1094 | |
| 1095 | Args: |
| 1096 | ip_int: An integer, the IP address. |
| 1097 | |
| 1098 | Returns: |
| 1099 | The IP address as a string in dotted decimal notation. |
| 1100 | |
| 1101 | """ |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1102 | return '.'.join(map(str, ip_int.to_bytes(4, 'big'))) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1103 | |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1104 | def _is_valid_netmask(self, netmask): |
| 1105 | """Verify that the netmask is valid. |
| 1106 | |
| 1107 | Args: |
| 1108 | netmask: A string, either a prefix or dotted decimal |
| 1109 | netmask. |
| 1110 | |
| 1111 | Returns: |
| 1112 | A boolean, True if the prefix represents a valid IPv4 |
| 1113 | netmask. |
| 1114 | |
| 1115 | """ |
| 1116 | mask = netmask.split('.') |
| 1117 | if len(mask) == 4: |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1118 | try: |
| 1119 | for x in mask: |
| 1120 | if int(x) not in self._valid_mask_octets: |
| 1121 | return False |
| 1122 | except ValueError: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1123 | # Found something that isn't an integer or isn't valid |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1124 | return False |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1125 | for idx, y in enumerate(mask): |
| 1126 | if idx > 0 and y > mask[idx - 1]: |
| 1127 | return False |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1128 | return True |
| 1129 | try: |
| 1130 | netmask = int(netmask) |
| 1131 | except ValueError: |
| 1132 | return False |
| 1133 | return 0 <= netmask <= self._max_prefixlen |
| 1134 | |
| 1135 | def _is_hostmask(self, ip_str): |
| 1136 | """Test if the IP string is a hostmask (rather than a netmask). |
| 1137 | |
| 1138 | Args: |
| 1139 | ip_str: A string, the potential hostmask. |
| 1140 | |
| 1141 | Returns: |
| 1142 | A boolean, True if the IP string is a hostmask. |
| 1143 | |
| 1144 | """ |
| 1145 | bits = ip_str.split('.') |
| 1146 | try: |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1147 | parts = [x for x in map(int, bits) if x in self._valid_mask_octets] |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1148 | except ValueError: |
| 1149 | return False |
| 1150 | if len(parts) != len(bits): |
| 1151 | return False |
| 1152 | if parts[0] < parts[-1]: |
| 1153 | return True |
| 1154 | return False |
| 1155 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1156 | @property |
| 1157 | def max_prefixlen(self): |
| 1158 | return self._max_prefixlen |
| 1159 | |
| 1160 | @property |
| 1161 | def version(self): |
| 1162 | return self._version |
| 1163 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1164 | |
| 1165 | class IPv4Address(_BaseV4, _BaseAddress): |
| 1166 | |
| 1167 | """Represent and manipulate single IPv4 Addresses.""" |
| 1168 | |
| 1169 | def __init__(self, address): |
| 1170 | |
| 1171 | """ |
| 1172 | Args: |
| 1173 | address: A string or integer representing the IP |
| 1174 | |
| 1175 | Additionally, an integer can be passed, so |
| 1176 | IPv4Address('192.0.2.1') == IPv4Address(3221225985). |
| 1177 | or, more generally |
| 1178 | IPv4Address(int(IPv4Address('192.0.2.1'))) == |
| 1179 | IPv4Address('192.0.2.1') |
| 1180 | |
| 1181 | Raises: |
Sandro Tosi | b4386d3 | 2012-06-02 17:14:22 +0200 | [diff] [blame] | 1182 | AddressValueError: If ipaddress isn't a valid IPv4 address. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1183 | |
| 1184 | """ |
| 1185 | _BaseAddress.__init__(self, address) |
| 1186 | _BaseV4.__init__(self, address) |
| 1187 | |
| 1188 | # Efficient constructor from integer. |
| 1189 | if isinstance(address, int): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1190 | self._check_int_address(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1191 | self._ip = address |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1192 | return |
| 1193 | |
| 1194 | # Constructing from a packed address |
Nick Coghlan | 5cf896f | 2012-07-07 01:43:31 +1000 | [diff] [blame] | 1195 | if isinstance(address, bytes): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1196 | self._check_packed_address(address, 4) |
Nick Coghlan | db7920b | 2012-08-20 10:19:12 +1000 | [diff] [blame] | 1197 | self._ip = int.from_bytes(address, 'big') |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1198 | return |
| 1199 | |
| 1200 | # Assume input argument to be string or any object representation |
| 1201 | # which converts into a formatted IP string. |
| 1202 | addr_str = str(address) |
| 1203 | self._ip = self._ip_int_from_string(addr_str) |
| 1204 | |
| 1205 | @property |
| 1206 | def packed(self): |
| 1207 | """The binary representation of this address.""" |
| 1208 | return v4_int_to_packed(self._ip) |
| 1209 | |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 1210 | @property |
| 1211 | def is_reserved(self): |
| 1212 | """Test if the address is otherwise IETF reserved. |
| 1213 | |
| 1214 | Returns: |
| 1215 | A boolean, True if the address is within the |
| 1216 | reserved IPv4 Network range. |
| 1217 | |
| 1218 | """ |
| 1219 | reserved_network = IPv4Network('240.0.0.0/4') |
| 1220 | return self in reserved_network |
| 1221 | |
| 1222 | @property |
| 1223 | def is_private(self): |
| 1224 | """Test if this address is allocated for private networks. |
| 1225 | |
| 1226 | Returns: |
| 1227 | A boolean, True if the address is reserved per RFC 1918. |
| 1228 | |
| 1229 | """ |
| 1230 | private_10 = IPv4Network('10.0.0.0/8') |
| 1231 | private_172 = IPv4Network('172.16.0.0/12') |
| 1232 | private_192 = IPv4Network('192.168.0.0/16') |
| 1233 | return (self in private_10 or |
| 1234 | self in private_172 or |
| 1235 | self in private_192) |
| 1236 | |
| 1237 | @property |
| 1238 | def is_multicast(self): |
| 1239 | """Test if the address is reserved for multicast use. |
| 1240 | |
| 1241 | Returns: |
| 1242 | A boolean, True if the address is multicast. |
| 1243 | See RFC 3171 for details. |
| 1244 | |
| 1245 | """ |
| 1246 | multicast_network = IPv4Network('224.0.0.0/4') |
| 1247 | return self in multicast_network |
| 1248 | |
| 1249 | @property |
| 1250 | def is_unspecified(self): |
| 1251 | """Test if the address is unspecified. |
| 1252 | |
| 1253 | Returns: |
| 1254 | A boolean, True if this is the unspecified address as defined in |
| 1255 | RFC 5735 3. |
| 1256 | |
| 1257 | """ |
| 1258 | unspecified_address = IPv4Address('0.0.0.0') |
| 1259 | return self == unspecified_address |
| 1260 | |
| 1261 | @property |
| 1262 | def is_loopback(self): |
| 1263 | """Test if the address is a loopback address. |
| 1264 | |
| 1265 | Returns: |
| 1266 | A boolean, True if the address is a loopback per RFC 3330. |
| 1267 | |
| 1268 | """ |
| 1269 | loopback_network = IPv4Network('127.0.0.0/8') |
| 1270 | return self in loopback_network |
| 1271 | |
| 1272 | @property |
| 1273 | def is_link_local(self): |
| 1274 | """Test if the address is reserved for link-local. |
| 1275 | |
| 1276 | Returns: |
| 1277 | A boolean, True if the address is link-local per RFC 3927. |
| 1278 | |
| 1279 | """ |
| 1280 | linklocal_network = IPv4Network('169.254.0.0/16') |
| 1281 | return self in linklocal_network |
| 1282 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1283 | |
| 1284 | class IPv4Interface(IPv4Address): |
| 1285 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1286 | def __init__(self, address): |
| 1287 | if isinstance(address, (bytes, int)): |
| 1288 | IPv4Address.__init__(self, address) |
| 1289 | self.network = IPv4Network(self._ip) |
| 1290 | self._prefixlen = self._max_prefixlen |
| 1291 | return |
| 1292 | |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1293 | addr = _split_optional_netmask(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1294 | IPv4Address.__init__(self, addr[0]) |
| 1295 | |
| 1296 | self.network = IPv4Network(address, strict=False) |
| 1297 | self._prefixlen = self.network._prefixlen |
| 1298 | |
| 1299 | self.netmask = self.network.netmask |
| 1300 | self.hostmask = self.network.hostmask |
| 1301 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1302 | def __str__(self): |
| 1303 | return '%s/%d' % (self._string_from_ip_int(self._ip), |
| 1304 | self.network.prefixlen) |
| 1305 | |
| 1306 | def __eq__(self, other): |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1307 | address_equal = IPv4Address.__eq__(self, other) |
| 1308 | if not address_equal or address_equal is NotImplemented: |
| 1309 | return address_equal |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1310 | try: |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1311 | return self.network == other.network |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1312 | except AttributeError: |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1313 | # An interface with an associated network is NOT the |
| 1314 | # same as an unassociated address. That's why the hash |
| 1315 | # takes the extra info into account. |
| 1316 | return False |
| 1317 | |
| 1318 | def __lt__(self, other): |
| 1319 | address_less = IPv4Address.__lt__(self, other) |
| 1320 | if address_less is NotImplemented: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1321 | return NotImplemented |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1322 | try: |
| 1323 | return self.network < other.network |
| 1324 | except AttributeError: |
| 1325 | # We *do* allow addresses and interfaces to be sorted. The |
| 1326 | # unassociated address is considered less than all interfaces. |
| 1327 | return False |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1328 | |
| 1329 | def __hash__(self): |
| 1330 | return self._ip ^ self._prefixlen ^ int(self.network.network_address) |
| 1331 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1332 | @property |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1333 | def ip(self): |
| 1334 | return IPv4Address(self._ip) |
| 1335 | |
| 1336 | @property |
| 1337 | def with_prefixlen(self): |
Nick Coghlan | a8517ad | 2012-08-20 10:04:26 +1000 | [diff] [blame] | 1338 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1339 | self._prefixlen) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1340 | |
| 1341 | @property |
| 1342 | def with_netmask(self): |
| 1343 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1344 | self.netmask) |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 1345 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1346 | @property |
| 1347 | def with_hostmask(self): |
| 1348 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1349 | self.hostmask) |
| 1350 | |
| 1351 | |
| 1352 | class IPv4Network(_BaseV4, _BaseNetwork): |
| 1353 | |
| 1354 | """This class represents and manipulates 32-bit IPv4 network + addresses.. |
| 1355 | |
| 1356 | Attributes: [examples for IPv4Network('192.0.2.0/27')] |
| 1357 | .network_address: IPv4Address('192.0.2.0') |
| 1358 | .hostmask: IPv4Address('0.0.0.31') |
| 1359 | .broadcast_address: IPv4Address('192.0.2.32') |
| 1360 | .netmask: IPv4Address('255.255.255.224') |
| 1361 | .prefixlen: 27 |
| 1362 | |
| 1363 | """ |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 1364 | # Class to use when creating address objects |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 1365 | _address_class = IPv4Address |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1366 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1367 | def __init__(self, address, strict=True): |
| 1368 | |
| 1369 | """Instantiate a new IPv4 network object. |
| 1370 | |
| 1371 | Args: |
| 1372 | address: A string or integer representing the IP [& network]. |
| 1373 | '192.0.2.0/24' |
| 1374 | '192.0.2.0/255.255.255.0' |
| 1375 | '192.0.0.2/0.0.0.255' |
| 1376 | are all functionally the same in IPv4. Similarly, |
| 1377 | '192.0.2.1' |
| 1378 | '192.0.2.1/255.255.255.255' |
| 1379 | '192.0.2.1/32' |
| 1380 | are also functionaly equivalent. That is to say, failing to |
| 1381 | provide a subnetmask will create an object with a mask of /32. |
| 1382 | |
| 1383 | If the mask (portion after the / in the argument) is given in |
| 1384 | dotted quad form, it is treated as a netmask if it starts with a |
| 1385 | non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it |
| 1386 | starts with a zero field (e.g. 0.255.255.255 == /8), with the |
| 1387 | single exception of an all-zero mask which is treated as a |
| 1388 | netmask == /0. If no mask is given, a default of /32 is used. |
| 1389 | |
| 1390 | Additionally, an integer can be passed, so |
| 1391 | IPv4Network('192.0.2.1') == IPv4Network(3221225985) |
| 1392 | or, more generally |
| 1393 | IPv4Interface(int(IPv4Interface('192.0.2.1'))) == |
| 1394 | IPv4Interface('192.0.2.1') |
| 1395 | |
| 1396 | Raises: |
Sandro Tosi | b4386d3 | 2012-06-02 17:14:22 +0200 | [diff] [blame] | 1397 | AddressValueError: If ipaddress isn't a valid IPv4 address. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1398 | NetmaskValueError: If the netmask isn't valid for |
| 1399 | an IPv4 address. |
Sandro Tosi | b4386d3 | 2012-06-02 17:14:22 +0200 | [diff] [blame] | 1400 | ValueError: If strict is True and a network address is not |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1401 | supplied. |
| 1402 | |
| 1403 | """ |
| 1404 | |
| 1405 | _BaseV4.__init__(self, address) |
| 1406 | _BaseNetwork.__init__(self, address) |
| 1407 | |
| 1408 | # Constructing from a packed address |
Nick Coghlan | 5cf896f | 2012-07-07 01:43:31 +1000 | [diff] [blame] | 1409 | if isinstance(address, bytes): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1410 | self.network_address = IPv4Address(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1411 | self._prefixlen = self._max_prefixlen |
| 1412 | self.netmask = IPv4Address(self._ALL_ONES) |
| 1413 | #fixme: address/network test here |
| 1414 | return |
| 1415 | |
| 1416 | # Efficient constructor from integer. |
| 1417 | if isinstance(address, int): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1418 | self.network_address = IPv4Address(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1419 | self._prefixlen = self._max_prefixlen |
| 1420 | self.netmask = IPv4Address(self._ALL_ONES) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1421 | #fixme: address/network test here. |
| 1422 | return |
| 1423 | |
| 1424 | # Assume input argument to be string or any object representation |
| 1425 | # which converts into a formatted IP prefix string. |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1426 | addr = _split_optional_netmask(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1427 | self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) |
| 1428 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1429 | if len(addr) == 2: |
| 1430 | mask = addr[1].split('.') |
| 1431 | |
| 1432 | if len(mask) == 4: |
| 1433 | # We have dotted decimal netmask. |
| 1434 | if self._is_valid_netmask(addr[1]): |
| 1435 | self.netmask = IPv4Address(self._ip_int_from_string( |
| 1436 | addr[1])) |
| 1437 | elif self._is_hostmask(addr[1]): |
| 1438 | self.netmask = IPv4Address( |
| 1439 | self._ip_int_from_string(addr[1]) ^ self._ALL_ONES) |
| 1440 | else: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1441 | raise NetmaskValueError('%r is not a valid netmask' |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1442 | % addr[1]) |
| 1443 | |
| 1444 | self._prefixlen = self._prefix_from_ip_int(int(self.netmask)) |
| 1445 | else: |
| 1446 | # We have a netmask in prefix length form. |
| 1447 | if not self._is_valid_netmask(addr[1]): |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1448 | raise NetmaskValueError('%r is not a valid netmask' |
| 1449 | % addr[1]) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1450 | self._prefixlen = int(addr[1]) |
| 1451 | self.netmask = IPv4Address(self._ip_int_from_prefix( |
| 1452 | self._prefixlen)) |
| 1453 | else: |
| 1454 | self._prefixlen = self._max_prefixlen |
| 1455 | self.netmask = IPv4Address(self._ip_int_from_prefix( |
| 1456 | self._prefixlen)) |
| 1457 | |
| 1458 | if strict: |
| 1459 | if (IPv4Address(int(self.network_address) & int(self.netmask)) != |
| 1460 | self.network_address): |
| 1461 | raise ValueError('%s has host bits set' % self) |
| 1462 | self.network_address = IPv4Address(int(self.network_address) & |
| 1463 | int(self.netmask)) |
| 1464 | |
| 1465 | if self._prefixlen == (self._max_prefixlen - 1): |
| 1466 | self.hosts = self.__iter__ |
| 1467 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1468 | |
Hynek Schlawack | c4b78a3 | 2012-06-01 11:48:32 +0200 | [diff] [blame] | 1469 | class _BaseV6: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1470 | |
| 1471 | """Base IPv6 object. |
| 1472 | |
| 1473 | The following methods are used by IPv6 objects in both single IP |
| 1474 | addresses and networks. |
| 1475 | |
| 1476 | """ |
| 1477 | |
| 1478 | _ALL_ONES = (2**IPV6LENGTH) - 1 |
| 1479 | _HEXTET_COUNT = 8 |
| 1480 | _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') |
| 1481 | |
| 1482 | def __init__(self, address): |
| 1483 | self._version = 6 |
| 1484 | self._max_prefixlen = IPV6LENGTH |
| 1485 | |
| 1486 | def _ip_int_from_string(self, ip_str): |
| 1487 | """Turn an IPv6 ip_str into an integer. |
| 1488 | |
| 1489 | Args: |
| 1490 | ip_str: A string, the IPv6 ip_str. |
| 1491 | |
| 1492 | Returns: |
| 1493 | An int, the IPv6 address |
| 1494 | |
| 1495 | Raises: |
| 1496 | AddressValueError: if ip_str isn't a valid IPv6 Address. |
| 1497 | |
| 1498 | """ |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1499 | if not ip_str: |
| 1500 | raise AddressValueError('Address cannot be empty') |
| 1501 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1502 | parts = ip_str.split(':') |
| 1503 | |
| 1504 | # An IPv6 address needs at least 2 colons (3 parts). |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1505 | _min_parts = 3 |
| 1506 | if len(parts) < _min_parts: |
| 1507 | msg = "At least %d parts expected in %r" % (_min_parts, ip_str) |
| 1508 | raise AddressValueError(msg) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1509 | |
| 1510 | # If the address has an IPv4-style suffix, convert it to hexadecimal. |
| 1511 | if '.' in parts[-1]: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1512 | try: |
| 1513 | ipv4_int = IPv4Address(parts.pop())._ip |
| 1514 | except AddressValueError as exc: |
| 1515 | raise AddressValueError("%s in %r" % (exc, ip_str)) from None |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1516 | parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) |
| 1517 | parts.append('%x' % (ipv4_int & 0xFFFF)) |
| 1518 | |
| 1519 | # An IPv6 address can't have more than 8 colons (9 parts). |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1520 | # The extra colon comes from using the "::" notation for a single |
| 1521 | # leading or trailing zero part. |
| 1522 | _max_parts = self._HEXTET_COUNT + 1 |
| 1523 | if len(parts) > _max_parts: |
| 1524 | msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) |
| 1525 | raise AddressValueError(msg) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1526 | |
| 1527 | # Disregarding the endpoints, find '::' with nothing in between. |
| 1528 | # This indicates that a run of zeroes has been skipped. |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1529 | skip_index = None |
| 1530 | for i in range(1, len(parts) - 1): |
| 1531 | if not parts[i]: |
| 1532 | if skip_index is not None: |
| 1533 | # Can't have more than one '::' |
| 1534 | msg = "At most one '::' permitted in %r" % ip_str |
| 1535 | raise AddressValueError(msg) |
| 1536 | skip_index = i |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1537 | |
| 1538 | # parts_hi is the number of parts to copy from above/before the '::' |
| 1539 | # parts_lo is the number of parts to copy from below/after the '::' |
| 1540 | if skip_index is not None: |
| 1541 | # If we found a '::', then check if it also covers the endpoints. |
| 1542 | parts_hi = skip_index |
| 1543 | parts_lo = len(parts) - skip_index - 1 |
| 1544 | if not parts[0]: |
| 1545 | parts_hi -= 1 |
| 1546 | if parts_hi: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1547 | msg = "Leading ':' only permitted as part of '::' in %r" |
| 1548 | raise AddressValueError(msg % ip_str) # ^: requires ^:: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1549 | if not parts[-1]: |
| 1550 | parts_lo -= 1 |
| 1551 | if parts_lo: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1552 | msg = "Trailing ':' only permitted as part of '::' in %r" |
| 1553 | raise AddressValueError(msg % ip_str) # :$ requires ::$ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1554 | parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) |
| 1555 | if parts_skipped < 1: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1556 | msg = "Expected at most %d other parts with '::' in %r" |
| 1557 | raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1558 | else: |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 1559 | # Otherwise, allocate the entire address to parts_hi. The |
| 1560 | # endpoints could still be empty, but _parse_hextet() will check |
| 1561 | # for that. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1562 | if len(parts) != self._HEXTET_COUNT: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1563 | msg = "Exactly %d parts expected without '::' in %r" |
| 1564 | raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) |
| 1565 | if not parts[0]: |
| 1566 | msg = "Leading ':' only permitted as part of '::' in %r" |
| 1567 | raise AddressValueError(msg % ip_str) # ^: requires ^:: |
| 1568 | if not parts[-1]: |
| 1569 | msg = "Trailing ':' only permitted as part of '::' in %r" |
| 1570 | raise AddressValueError(msg % ip_str) # :$ requires ::$ |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1571 | parts_hi = len(parts) |
| 1572 | parts_lo = 0 |
| 1573 | parts_skipped = 0 |
| 1574 | |
| 1575 | try: |
| 1576 | # Now, parse the hextets into a 128-bit integer. |
| 1577 | ip_int = 0 |
| 1578 | for i in range(parts_hi): |
| 1579 | ip_int <<= 16 |
| 1580 | ip_int |= self._parse_hextet(parts[i]) |
| 1581 | ip_int <<= 16 * parts_skipped |
| 1582 | for i in range(-parts_lo, 0): |
| 1583 | ip_int <<= 16 |
| 1584 | ip_int |= self._parse_hextet(parts[i]) |
| 1585 | return ip_int |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1586 | except ValueError as exc: |
| 1587 | raise AddressValueError("%s in %r" % (exc, ip_str)) from None |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1588 | |
| 1589 | def _parse_hextet(self, hextet_str): |
| 1590 | """Convert an IPv6 hextet string into an integer. |
| 1591 | |
| 1592 | Args: |
| 1593 | hextet_str: A string, the number to parse. |
| 1594 | |
| 1595 | Returns: |
| 1596 | The hextet as an integer. |
| 1597 | |
| 1598 | Raises: |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 1599 | ValueError: if the input isn't strictly a hex number from |
| 1600 | [0..FFFF]. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1601 | |
| 1602 | """ |
| 1603 | # Whitelist the characters, since int() allows a lot of bizarre stuff. |
| 1604 | if not self._HEX_DIGITS.issuperset(hextet_str): |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1605 | raise ValueError("Only hex digits permitted in %r" % hextet_str) |
Nick Coghlan | 07c4e33 | 2012-07-08 23:06:45 +1000 | [diff] [blame] | 1606 | # We do the length check second, since the invalid character error |
| 1607 | # is likely to be more informative for the user |
Nick Coghlan | 3c2570c | 2012-07-07 01:13:55 +1000 | [diff] [blame] | 1608 | if len(hextet_str) > 4: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1609 | msg = "At most 4 characters permitted in %r" |
| 1610 | raise ValueError(msg % hextet_str) |
Nick Coghlan | 07c4e33 | 2012-07-08 23:06:45 +1000 | [diff] [blame] | 1611 | # Length check means we can skip checking the integer value |
| 1612 | return int(hextet_str, 16) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1613 | |
| 1614 | def _compress_hextets(self, hextets): |
| 1615 | """Compresses a list of hextets. |
| 1616 | |
| 1617 | Compresses a list of strings, replacing the longest continuous |
| 1618 | sequence of "0" in the list with "" and adding empty strings at |
| 1619 | the beginning or at the end of the string such that subsequently |
| 1620 | calling ":".join(hextets) will produce the compressed version of |
| 1621 | the IPv6 address. |
| 1622 | |
| 1623 | Args: |
| 1624 | hextets: A list of strings, the hextets to compress. |
| 1625 | |
| 1626 | Returns: |
| 1627 | A list of strings. |
| 1628 | |
| 1629 | """ |
| 1630 | best_doublecolon_start = -1 |
| 1631 | best_doublecolon_len = 0 |
| 1632 | doublecolon_start = -1 |
| 1633 | doublecolon_len = 0 |
Nick Coghlan | db7920b | 2012-08-20 10:19:12 +1000 | [diff] [blame] | 1634 | for index, hextet in enumerate(hextets): |
| 1635 | if hextet == '0': |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1636 | doublecolon_len += 1 |
| 1637 | if doublecolon_start == -1: |
| 1638 | # Start of a sequence of zeros. |
| 1639 | doublecolon_start = index |
| 1640 | if doublecolon_len > best_doublecolon_len: |
| 1641 | # This is the longest sequence of zeros so far. |
| 1642 | best_doublecolon_len = doublecolon_len |
| 1643 | best_doublecolon_start = doublecolon_start |
| 1644 | else: |
| 1645 | doublecolon_len = 0 |
| 1646 | doublecolon_start = -1 |
| 1647 | |
| 1648 | if best_doublecolon_len > 1: |
| 1649 | best_doublecolon_end = (best_doublecolon_start + |
| 1650 | best_doublecolon_len) |
| 1651 | # For zeros at the end of the address. |
| 1652 | if best_doublecolon_end == len(hextets): |
| 1653 | hextets += [''] |
| 1654 | hextets[best_doublecolon_start:best_doublecolon_end] = [''] |
| 1655 | # For zeros at the beginning of the address. |
| 1656 | if best_doublecolon_start == 0: |
| 1657 | hextets = [''] + hextets |
| 1658 | |
| 1659 | return hextets |
| 1660 | |
| 1661 | def _string_from_ip_int(self, ip_int=None): |
| 1662 | """Turns a 128-bit integer into hexadecimal notation. |
| 1663 | |
| 1664 | Args: |
| 1665 | ip_int: An integer, the IP address. |
| 1666 | |
| 1667 | Returns: |
| 1668 | A string, the hexadecimal representation of the address. |
| 1669 | |
| 1670 | Raises: |
| 1671 | ValueError: The address is bigger than 128 bits of all ones. |
| 1672 | |
| 1673 | """ |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1674 | if ip_int is None: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1675 | ip_int = int(self._ip) |
| 1676 | |
| 1677 | if ip_int > self._ALL_ONES: |
| 1678 | raise ValueError('IPv6 address is too large') |
| 1679 | |
| 1680 | hex_str = '%032x' % ip_int |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1681 | hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1682 | |
| 1683 | hextets = self._compress_hextets(hextets) |
| 1684 | return ':'.join(hextets) |
| 1685 | |
| 1686 | def _explode_shorthand_ip_string(self): |
| 1687 | """Expand a shortened IPv6 address. |
| 1688 | |
| 1689 | Args: |
| 1690 | ip_str: A string, the IPv6 address. |
| 1691 | |
| 1692 | Returns: |
| 1693 | A string, the expanded IPv6 address. |
| 1694 | |
| 1695 | """ |
| 1696 | if isinstance(self, IPv6Network): |
| 1697 | ip_str = str(self.network_address) |
| 1698 | elif isinstance(self, IPv6Interface): |
| 1699 | ip_str = str(self.ip) |
| 1700 | else: |
| 1701 | ip_str = str(self) |
| 1702 | |
| 1703 | ip_int = self._ip_int_from_string(ip_str) |
Nick Coghlan | 7319f69 | 2012-07-07 21:43:30 +1000 | [diff] [blame] | 1704 | hex_str = '%032x' % ip_int |
| 1705 | parts = [hex_str[x:x+4] for x in range(0, 32, 4)] |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1706 | if isinstance(self, (_BaseNetwork, IPv6Interface)): |
Nick Coghlan | e3ded95 | 2012-08-05 22:45:22 +1000 | [diff] [blame] | 1707 | return '%s/%d' % (':'.join(parts), self._prefixlen) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1708 | return ':'.join(parts) |
| 1709 | |
| 1710 | @property |
| 1711 | def max_prefixlen(self): |
| 1712 | return self._max_prefixlen |
| 1713 | |
| 1714 | @property |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1715 | def version(self): |
| 1716 | return self._version |
| 1717 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1718 | |
| 1719 | class IPv6Address(_BaseV6, _BaseAddress): |
| 1720 | |
Sandro Tosi | b95c634 | 2012-05-23 23:17:22 +0200 | [diff] [blame] | 1721 | """Represent and manipulate single IPv6 Addresses.""" |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1722 | |
| 1723 | def __init__(self, address): |
| 1724 | """Instantiate a new IPv6 address object. |
| 1725 | |
| 1726 | Args: |
| 1727 | address: A string or integer representing the IP |
| 1728 | |
| 1729 | Additionally, an integer can be passed, so |
| 1730 | IPv6Address('2001:db8::') == |
| 1731 | IPv6Address(42540766411282592856903984951653826560) |
| 1732 | or, more generally |
| 1733 | IPv6Address(int(IPv6Address('2001:db8::'))) == |
| 1734 | IPv6Address('2001:db8::') |
| 1735 | |
| 1736 | Raises: |
| 1737 | AddressValueError: If address isn't a valid IPv6 address. |
| 1738 | |
| 1739 | """ |
| 1740 | _BaseAddress.__init__(self, address) |
| 1741 | _BaseV6.__init__(self, address) |
| 1742 | |
| 1743 | # Efficient constructor from integer. |
| 1744 | if isinstance(address, int): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1745 | self._check_int_address(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1746 | self._ip = address |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1747 | return |
| 1748 | |
| 1749 | # Constructing from a packed address |
Nick Coghlan | 5cf896f | 2012-07-07 01:43:31 +1000 | [diff] [blame] | 1750 | if isinstance(address, bytes): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 1751 | self._check_packed_address(address, 16) |
Nick Coghlan | db7920b | 2012-08-20 10:19:12 +1000 | [diff] [blame] | 1752 | self._ip = int.from_bytes(address, 'big') |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1753 | return |
| 1754 | |
| 1755 | # Assume input argument to be string or any object representation |
| 1756 | # which converts into a formatted IP string. |
| 1757 | addr_str = str(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1758 | self._ip = self._ip_int_from_string(addr_str) |
| 1759 | |
Hynek Schlawack | 91c5a34 | 2012-06-05 11:55:58 +0200 | [diff] [blame] | 1760 | @property |
| 1761 | def packed(self): |
| 1762 | """The binary representation of this address.""" |
| 1763 | return v6_int_to_packed(self._ip) |
| 1764 | |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 1765 | @property |
| 1766 | def is_multicast(self): |
| 1767 | """Test if the address is reserved for multicast use. |
| 1768 | |
| 1769 | Returns: |
| 1770 | A boolean, True if the address is a multicast address. |
| 1771 | See RFC 2373 2.7 for details. |
| 1772 | |
| 1773 | """ |
| 1774 | multicast_network = IPv6Network('ff00::/8') |
| 1775 | return self in multicast_network |
| 1776 | |
| 1777 | @property |
| 1778 | def is_reserved(self): |
| 1779 | """Test if the address is otherwise IETF reserved. |
| 1780 | |
| 1781 | Returns: |
| 1782 | A boolean, True if the address is within one of the |
| 1783 | reserved IPv6 Network ranges. |
| 1784 | |
| 1785 | """ |
| 1786 | reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), |
| 1787 | IPv6Network('200::/7'), IPv6Network('400::/6'), |
| 1788 | IPv6Network('800::/5'), IPv6Network('1000::/4'), |
| 1789 | IPv6Network('4000::/3'), IPv6Network('6000::/3'), |
| 1790 | IPv6Network('8000::/3'), IPv6Network('A000::/3'), |
| 1791 | IPv6Network('C000::/3'), IPv6Network('E000::/4'), |
| 1792 | IPv6Network('F000::/5'), IPv6Network('F800::/6'), |
| 1793 | IPv6Network('FE00::/9')] |
| 1794 | |
| 1795 | return any(self in x for x in reserved_networks) |
| 1796 | |
| 1797 | @property |
| 1798 | def is_link_local(self): |
| 1799 | """Test if the address is reserved for link-local. |
| 1800 | |
| 1801 | Returns: |
| 1802 | A boolean, True if the address is reserved per RFC 4291. |
| 1803 | |
| 1804 | """ |
| 1805 | linklocal_network = IPv6Network('fe80::/10') |
| 1806 | return self in linklocal_network |
| 1807 | |
| 1808 | @property |
| 1809 | def is_site_local(self): |
| 1810 | """Test if the address is reserved for site-local. |
| 1811 | |
| 1812 | Note that the site-local address space has been deprecated by RFC 3879. |
| 1813 | Use is_private to test if this address is in the space of unique local |
| 1814 | addresses as defined by RFC 4193. |
| 1815 | |
| 1816 | Returns: |
| 1817 | A boolean, True if the address is reserved per RFC 3513 2.5.6. |
| 1818 | |
| 1819 | """ |
| 1820 | sitelocal_network = IPv6Network('fec0::/10') |
| 1821 | return self in sitelocal_network |
| 1822 | |
| 1823 | @property |
| 1824 | def is_private(self): |
| 1825 | """Test if this address is allocated for private networks. |
| 1826 | |
| 1827 | Returns: |
| 1828 | A boolean, True if the address is reserved per RFC 4193. |
| 1829 | |
| 1830 | """ |
| 1831 | private_network = IPv6Network('fc00::/7') |
| 1832 | return self in private_network |
| 1833 | |
| 1834 | @property |
| 1835 | def is_unspecified(self): |
| 1836 | """Test if the address is unspecified. |
| 1837 | |
| 1838 | Returns: |
| 1839 | A boolean, True if this is the unspecified address as defined in |
| 1840 | RFC 2373 2.5.2. |
| 1841 | |
| 1842 | """ |
| 1843 | return self._ip == 0 |
| 1844 | |
| 1845 | @property |
| 1846 | def is_loopback(self): |
| 1847 | """Test if the address is a loopback address. |
| 1848 | |
| 1849 | Returns: |
| 1850 | A boolean, True if the address is a loopback address as defined in |
| 1851 | RFC 2373 2.5.3. |
| 1852 | |
| 1853 | """ |
| 1854 | return self._ip == 1 |
| 1855 | |
| 1856 | @property |
| 1857 | def ipv4_mapped(self): |
| 1858 | """Return the IPv4 mapped address. |
| 1859 | |
| 1860 | Returns: |
| 1861 | If the IPv6 address is a v4 mapped address, return the |
| 1862 | IPv4 mapped address. Return None otherwise. |
| 1863 | |
| 1864 | """ |
| 1865 | if (self._ip >> 32) != 0xFFFF: |
| 1866 | return None |
| 1867 | return IPv4Address(self._ip & 0xFFFFFFFF) |
| 1868 | |
| 1869 | @property |
| 1870 | def teredo(self): |
| 1871 | """Tuple of embedded teredo IPs. |
| 1872 | |
| 1873 | Returns: |
| 1874 | Tuple of the (server, client) IPs or None if the address |
| 1875 | doesn't appear to be a teredo address (doesn't start with |
| 1876 | 2001::/32) |
| 1877 | |
| 1878 | """ |
| 1879 | if (self._ip >> 96) != 0x20010000: |
| 1880 | return None |
| 1881 | return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), |
| 1882 | IPv4Address(~self._ip & 0xFFFFFFFF)) |
| 1883 | |
| 1884 | @property |
| 1885 | def sixtofour(self): |
| 1886 | """Return the IPv4 6to4 embedded address. |
| 1887 | |
| 1888 | Returns: |
| 1889 | The IPv4 6to4-embedded address if present or None if the |
| 1890 | address doesn't appear to contain a 6to4 embedded address. |
| 1891 | |
| 1892 | """ |
| 1893 | if (self._ip >> 112) != 0x2002: |
| 1894 | return None |
| 1895 | return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) |
| 1896 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1897 | |
| 1898 | class IPv6Interface(IPv6Address): |
| 1899 | |
| 1900 | def __init__(self, address): |
| 1901 | if isinstance(address, (bytes, int)): |
| 1902 | IPv6Address.__init__(self, address) |
| 1903 | self.network = IPv6Network(self._ip) |
| 1904 | self._prefixlen = self._max_prefixlen |
| 1905 | return |
| 1906 | |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 1907 | addr = _split_optional_netmask(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1908 | IPv6Address.__init__(self, addr[0]) |
| 1909 | self.network = IPv6Network(address, strict=False) |
| 1910 | self.netmask = self.network.netmask |
| 1911 | self._prefixlen = self.network._prefixlen |
| 1912 | self.hostmask = self.network.hostmask |
| 1913 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1914 | def __str__(self): |
| 1915 | return '%s/%d' % (self._string_from_ip_int(self._ip), |
| 1916 | self.network.prefixlen) |
| 1917 | |
| 1918 | def __eq__(self, other): |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1919 | address_equal = IPv6Address.__eq__(self, other) |
| 1920 | if not address_equal or address_equal is NotImplemented: |
| 1921 | return address_equal |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1922 | try: |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1923 | return self.network == other.network |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1924 | except AttributeError: |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1925 | # An interface with an associated network is NOT the |
| 1926 | # same as an unassociated address. That's why the hash |
| 1927 | # takes the extra info into account. |
| 1928 | return False |
| 1929 | |
| 1930 | def __lt__(self, other): |
| 1931 | address_less = IPv6Address.__lt__(self, other) |
| 1932 | if address_less is NotImplemented: |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1933 | return NotImplemented |
Nick Coghlan | 3008ec0 | 2012-07-08 00:45:33 +1000 | [diff] [blame] | 1934 | try: |
| 1935 | return self.network < other.network |
| 1936 | except AttributeError: |
| 1937 | # We *do* allow addresses and interfaces to be sorted. The |
| 1938 | # unassociated address is considered less than all interfaces. |
| 1939 | return False |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1940 | |
| 1941 | def __hash__(self): |
| 1942 | return self._ip ^ self._prefixlen ^ int(self.network.network_address) |
| 1943 | |
| 1944 | @property |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1945 | def ip(self): |
| 1946 | return IPv6Address(self._ip) |
| 1947 | |
| 1948 | @property |
| 1949 | def with_prefixlen(self): |
Nick Coghlan | a8517ad | 2012-08-20 10:04:26 +1000 | [diff] [blame] | 1950 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1951 | self._prefixlen) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1952 | |
| 1953 | @property |
| 1954 | def with_netmask(self): |
Nick Coghlan | a8517ad | 2012-08-20 10:04:26 +1000 | [diff] [blame] | 1955 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1956 | self.netmask) |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 1957 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1958 | @property |
| 1959 | def with_hostmask(self): |
| 1960 | return '%s/%s' % (self._string_from_ip_int(self._ip), |
| 1961 | self.hostmask) |
| 1962 | |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 1963 | @property |
| 1964 | def is_unspecified(self): |
| 1965 | return self._ip == 0 and self.network.is_unspecified |
| 1966 | |
| 1967 | @property |
| 1968 | def is_loopback(self): |
| 1969 | return self._ip == 1 and self.network.is_loopback |
| 1970 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1971 | |
| 1972 | class IPv6Network(_BaseV6, _BaseNetwork): |
| 1973 | |
| 1974 | """This class represents and manipulates 128-bit IPv6 networks. |
| 1975 | |
| 1976 | Attributes: [examples for IPv6('2001:db8::1000/124')] |
| 1977 | .network_address: IPv6Address('2001:db8::1000') |
| 1978 | .hostmask: IPv6Address('::f') |
| 1979 | .broadcast_address: IPv6Address('2001:db8::100f') |
| 1980 | .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') |
| 1981 | .prefixlen: 124 |
| 1982 | |
| 1983 | """ |
| 1984 | |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 1985 | # Class to use when creating address objects |
Nick Coghlan | 51c3067 | 2012-05-27 00:25:58 +1000 | [diff] [blame] | 1986 | _address_class = IPv6Address |
| 1987 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1988 | def __init__(self, address, strict=True): |
| 1989 | """Instantiate a new IPv6 Network object. |
| 1990 | |
| 1991 | Args: |
Hynek Schlawack | 072b1e1 | 2012-05-26 12:04:56 +0200 | [diff] [blame] | 1992 | address: A string or integer representing the IPv6 network or the |
| 1993 | IP and prefix/netmask. |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 1994 | '2001:db8::/128' |
| 1995 | '2001:db8:0000:0000:0000:0000:0000:0000/128' |
| 1996 | '2001:db8::' |
| 1997 | are all functionally the same in IPv6. That is to say, |
| 1998 | failing to provide a subnetmask will create an object with |
| 1999 | a mask of /128. |
| 2000 | |
| 2001 | Additionally, an integer can be passed, so |
| 2002 | IPv6Network('2001:db8::') == |
| 2003 | IPv6Network(42540766411282592856903984951653826560) |
| 2004 | or, more generally |
| 2005 | IPv6Network(int(IPv6Network('2001:db8::'))) == |
| 2006 | IPv6Network('2001:db8::') |
| 2007 | |
| 2008 | strict: A boolean. If true, ensure that we have been passed |
| 2009 | A true network address, eg, 2001:db8::1000/124 and not an |
| 2010 | IP address on a network, eg, 2001:db8::1/124. |
| 2011 | |
| 2012 | Raises: |
| 2013 | AddressValueError: If address isn't a valid IPv6 address. |
| 2014 | NetmaskValueError: If the netmask isn't valid for |
| 2015 | an IPv6 address. |
| 2016 | ValueError: If strict was True and a network address was not |
| 2017 | supplied. |
| 2018 | |
| 2019 | """ |
| 2020 | _BaseV6.__init__(self, address) |
| 2021 | _BaseNetwork.__init__(self, address) |
| 2022 | |
| 2023 | # Efficient constructor from integer. |
| 2024 | if isinstance(address, int): |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2025 | self.network_address = IPv6Address(address) |
| 2026 | self._prefixlen = self._max_prefixlen |
| 2027 | self.netmask = IPv6Address(self._ALL_ONES) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2028 | return |
| 2029 | |
| 2030 | # Constructing from a packed address |
Nick Coghlan | 5cf896f | 2012-07-07 01:43:31 +1000 | [diff] [blame] | 2031 | if isinstance(address, bytes): |
Nick Coghlan | 297b143 | 2012-07-08 17:11:04 +1000 | [diff] [blame] | 2032 | self.network_address = IPv6Address(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2033 | self._prefixlen = self._max_prefixlen |
| 2034 | self.netmask = IPv6Address(self._ALL_ONES) |
Hynek Schlawack | ed36b2e | 2012-06-08 15:21:21 +0200 | [diff] [blame] | 2035 | return |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2036 | |
| 2037 | # Assume input argument to be string or any object representation |
| 2038 | # which converts into a formatted IP prefix string. |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 2039 | addr = _split_optional_netmask(address) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2040 | |
| 2041 | self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) |
| 2042 | |
| 2043 | if len(addr) == 2: |
| 2044 | if self._is_valid_netmask(addr[1]): |
| 2045 | self._prefixlen = int(addr[1]) |
| 2046 | else: |
Nick Coghlan | 36f8dcd | 2012-07-07 19:23:53 +1000 | [diff] [blame] | 2047 | raise NetmaskValueError('%r is not a valid netmask' |
| 2048 | % addr[1]) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2049 | else: |
| 2050 | self._prefixlen = self._max_prefixlen |
| 2051 | |
| 2052 | self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) |
| 2053 | if strict: |
| 2054 | if (IPv6Address(int(self.network_address) & int(self.netmask)) != |
| 2055 | self.network_address): |
Nick Coghlan | 912238e | 2012-07-07 13:34:50 +1000 | [diff] [blame] | 2056 | raise ValueError('%s has host bits set' % self) |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2057 | self.network_address = IPv6Address(int(self.network_address) & |
| 2058 | int(self.netmask)) |
| 2059 | |
| 2060 | if self._prefixlen == (self._max_prefixlen - 1): |
| 2061 | self.hosts = self.__iter__ |
| 2062 | |
Nick Coghlan | dc9b255 | 2012-05-20 21:01:57 +1000 | [diff] [blame] | 2063 | def _is_valid_netmask(self, prefixlen): |
| 2064 | """Verify that the netmask/prefixlen is valid. |
| 2065 | |
| 2066 | Args: |
| 2067 | prefixlen: A string, the netmask in prefix length format. |
| 2068 | |
| 2069 | Returns: |
| 2070 | A boolean, True if the prefix represents a valid IPv6 |
| 2071 | netmask. |
| 2072 | |
| 2073 | """ |
| 2074 | try: |
| 2075 | prefixlen = int(prefixlen) |
| 2076 | except ValueError: |
| 2077 | return False |
| 2078 | return 0 <= prefixlen <= self._max_prefixlen |
Nick Coghlan | 730f67f | 2012-08-05 22:02:18 +1000 | [diff] [blame] | 2079 | |
| 2080 | @property |
| 2081 | def is_site_local(self): |
| 2082 | """Test if the address is reserved for site-local. |
| 2083 | |
| 2084 | Note that the site-local address space has been deprecated by RFC 3879. |
| 2085 | Use is_private to test if this address is in the space of unique local |
| 2086 | addresses as defined by RFC 4193. |
| 2087 | |
| 2088 | Returns: |
| 2089 | A boolean, True if the address is reserved per RFC 3513 2.5.6. |
| 2090 | |
| 2091 | """ |
| 2092 | return (self.network_address.is_site_local and |
| 2093 | self.broadcast_address.is_site_local) |