Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [
(first, last)
| 195 | |
| 196 | |
| 197 | def summarize_address_range(first, last): |
| 198 | """Summarize a network range given the first and last IP addresses. |
| 199 | |
| 200 | Example: |
| 201 | >>> list(summarize_address_range(IPv4Address('192.0.2.0'), |
| 202 | ... IPv4Address('192.0.2.130'))) |
| 203 | ... #doctest: +NORMALIZE_WHITESPACE |
| 204 | [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), |
| 205 | IPv4Network('192.0.2.130/32')] |
| 206 | |
| 207 | Args: |
| 208 | first: the first IPv4Address or IPv6Address in the range. |
| 209 | last: the last IPv4Address or IPv6Address in the range. |
| 210 | |
| 211 | Returns: |
| 212 | An iterator of the summarized IPv(4|6) network objects. |
| 213 | |
| 214 | Raise: |
| 215 | TypeError: |
| 216 | If the first and last objects are not IP addresses. |
| 217 | If the first and last objects are not the same version. |
| 218 | ValueError: |
| 219 | If the last object is not greater than the first. |
| 220 | If the version of the first address is not 4 or 6. |
| 221 | |
| 222 | """ |
| 223 | if (not (isinstance(first, _BaseAddress) and |
| 224 | isinstance(last, _BaseAddress))): |
| 225 | raise TypeError('first and last must be IP addresses, not networks') |
| 226 | if first.version != last.version: |
| 227 | raise TypeError("%s and %s are not of the same version" % ( |
| 228 | first, last)) |
| 229 | if first > last: |
| 230 | raise ValueError('last IP address must be greater than first') |
| 231 | |
| 232 | if first.version == 4: |
| 233 | ip = IPv4Network |
| 234 | elif first.version == 6: |
| 235 | ip = IPv6Network |
| 236 | else: |
| 237 | raise ValueError('unknown IP version') |
| 238 | |
| 239 | ip_bits = first.max_prefixlen |
| 240 | first_int = first._ip |
| 241 | last_int = last._ip |
| 242 | while first_int <= last_int: |
| 243 | nbits = min(_count_righthand_zero_bits(first_int, ip_bits), |
| 244 | (last_int - first_int + 1).bit_length() - 1) |
| 245 | net = ip((first_int, ip_bits - nbits)) |
| 246 | yield net |
| 247 | first_int += 1 << nbits |
| 248 | if first_int - 1 == ip._ALL_ONES: |
| 249 | break |
| 250 | |
| 251 | |
| 252 | def _collapse_addresses_internal(addresses): |
no test coverage detected
searching dependent graphs…