~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Lib/ipaddress.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

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