1
# Copyright 2007 Google Inc.
2
# Licensed to PSF under a Contributor Agreement.
4
"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
6
This library is used to create/poke/manipulate IPv4 and IPv6 addresses
19
class AddressValueError(ValueError):
20
"""A Value Error related to the address."""
23
class NetmaskValueError(ValueError):
24
"""A Value Error related to the netmask."""
27
def ip_address(address):
28
"""Take an IP string/int and return an object of the correct type.
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.
36
An IPv4Address or IPv6Address object.
39
ValueError: if the *address* passed isn't either a v4 or a v6
44
return IPv4Address(address)
45
except (AddressValueError, NetmaskValueError):
49
return IPv6Address(address)
50
except (AddressValueError, NetmaskValueError):
53
raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
57
def ip_network(address, strict=True):
58
"""Take an IP string/int and return an object of the correct type.
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.
66
An IPv4Network or IPv6Network object.
69
ValueError: if the string passed isn't either a v4 or a v6
70
address. Or if the network has host bits set.
74
return IPv4Network(address, strict)
75
except (AddressValueError, NetmaskValueError):
79
return IPv6Network(address, strict)
80
except (AddressValueError, NetmaskValueError):
83
raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
87
def ip_interface(address):
88
"""Take an IP string/int and return an object of the correct type.
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.
96
An IPv4Interface or IPv6Interface object.
99
ValueError: if the string passed isn't either a v4 or a v6
103
The IPv?Interface classes describe an Address on a particular
104
Network, so they're basically a combination of both the Address
109
return IPv4Interface(address)
110
except (AddressValueError, NetmaskValueError):
114
return IPv6Interface(address)
115
except (AddressValueError, NetmaskValueError):
118
raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
122
def v4_int_to_packed(address):
123
"""Represent an address as 4 packed bytes in network (big-endian) order.
126
address: An integer representation of an IPv4 IP address.
129
The integer address packed as 4 bytes in network (big-endian) order.
132
ValueError: If the integer is negative or too large to be an
137
return address.to_bytes(4, 'big')
139
raise ValueError("Address negative or too large for IPv4")
142
def v6_int_to_packed(address):
143
"""Represent an address as 16 packed bytes in network (big-endian) order.
146
address: An integer representation of an IPv6 IP address.
149
The integer address packed as 16 bytes in network (big-endian) order.
153
return address.to_bytes(16, 'big')
155
raise ValueError("Address negative or too large for IPv6")
158
def _split_optional_netmask(address):
159
"""Helper to split the netmask and raise AddressValueError if needed"""
160
addr = str(address).split('/')
162
raise AddressValueError("Only one '/' permitted in %r" % address)
166
def _find_address_range(addresses):
167
"""Find a sequence of IPv#Address.
170
addresses: a list of IPv#Address objects.
173
A tuple containing the first and last IP addresses in the sequence.
176
first = last = addresses[0]
177
for ip in addresses[1:]:
178
if ip._ip == last._ip + 1:
185
def _count_righthand_zero_bits(number, bits):
186
"""Count the number of zero bits on the right hand side.
190
bits: maximum number of bits to count.
193
The number of zero bits on the right hand side of the number.
198
for i in range(bits):
199
if (number >> i) & 1:
201
# All bits of interest were zero, even if there are more in the number
205
def summarize_address_range(first, last):
206
"""Summarize a network range given the first and last IP addresses.
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')]
216
first: the first IPv4Address or IPv6Address in the range.
217
last: the last IPv4Address or IPv6Address in the range.
220
An iterator of the summarized IPv(4|6) network objects.
224
If the first and last objects are not IP addresses.
225
If the first and last objects are not the same version.
227
If the last object is not greater than the first.
228
If the version of the first address is not 4 or 6.
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" % (
238
raise ValueError('last IP address must be greater than first')
240
if first.version == 4:
242
elif first.version == 6:
245
raise ValueError('unknown IP version')
247
ip_bits = first._max_prefixlen
248
first_int = first._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))
255
first_int += 1 << nbits
256
if first_int - 1 == ip._ALL_ONES:
258
first = first.__class__(first_int)
261
def _collapse_addresses_recursive(addresses):
262
"""Loops through the addresses, collapsing concurrent netblocks.
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')
271
_collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
272
[IPv4Network('192.0.2.0/24')]
274
This shouldn't be called directly; it is called via
275
collapse_addresses([]).
278
addresses: A list of IPv4Network's or IPv6Network's
281
A list of IPv4Network's or IPv6Network's depending on what we were
290
for cur_addr in addresses:
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):
297
elif cur_addr == list(last_addr.supernet().subnets())[1]:
298
ret_array[-1] = last_addr = last_addr.supernet()
302
ret_array.append(cur_addr)
304
addresses = ret_array
309
def collapse_addresses(addresses):
310
"""Collapse a list of IP objects.
313
collapse_addresses([IPv4Network('192.0.2.0/25'),
314
IPv4Network('192.0.2.128/25')]) ->
315
[IPv4Network('192.0.2.0/24')]
318
addresses: An iterator of IPv4Network or IPv6Network objects.
321
An iterator of the collapsed IPv(4|6)Network objects.
324
TypeError: If passed a list of mixed version objects.
332
# split IP addresses and networks
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" % (
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" % (
345
except AttributeError:
346
ips.append(ip.network_address)
348
if nets and nets[-1]._version != ip._version:
349
raise TypeError("%s and %s are not of the same version" % (
354
ips = sorted(set(ips))
355
nets = sorted(set(nets))
358
(first, last) = _find_address_range(ips[i:])
359
i = ips.index(last) + 1
360
addrs.extend(summarize_address_range(first, last))
362
return iter(_collapse_addresses_recursive(sorted(
363
addrs + nets, key=_BaseNetwork._get_networks_key)))
366
def get_mixed_type_key(obj):
367
"""Return a key suitable for sorting between networks and addresses.
369
Address and Network objects are not sortable by default; they're
370
fundamentally different so the expression
372
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
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().
379
obj: either a Network or Address object.
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
391
class _TotalOrderingMixin:
392
# Helper that derives the other comparison operations from
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
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)
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
424
class _IPAddressBase(_TotalOrderingMixin):
426
"""The mother class."""
430
"""Return the longhand version of the IP address as a string."""
431
return self._explode_shorthand_ip_string()
434
def compressed(self):
435
"""Return the shorthand version of the IP address as a string."""
440
msg = '%200s has no version specified' % (type(self),)
441
raise NotImplementedError(msg)
443
def _check_int_address(self, address):
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,
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))
459
def _ip_int_from_prefix(self, prefixlen=None):
460
"""Turn the prefix length netmask into a int for comparison.
463
prefixlen: An integer, the prefix length.
469
if prefixlen is None:
470
prefixlen = self._prefixlen
471
return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
473
def _prefix_from_ip_int(self, ip_int, mask=32):
474
"""Return prefix length from the decimal netmask.
477
ip_int: An integer, the IP address.
478
mask: The netmask. Defaults to 32.
481
An integer, the prefix length.
484
return mask - _count_righthand_zero_bits(ip_int, mask)
486
def _ip_string_from_prefix(self, prefixlen=None):
487
"""Turn a prefix length into a dotted decimal string.
490
prefixlen: An integer, the netmask prefix length.
493
A string, the dotted decimal netmask string.
497
prefixlen = self._prefixlen
498
return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
501
class _BaseAddress(_IPAddressBase):
503
"""A generic IP object.
505
This IP class contains the version independent methods which are
506
used by single IP addresses.
510
def __init__(self, address):
511
if (not isinstance(address, bytes)
512
and '/' in str(address)):
513
raise AddressValueError("Unexpected '/' in %r" % address)
518
def __eq__(self, other):
520
return (self._ip == other._ip
521
and self._version == other._version)
522
except AttributeError:
523
return NotImplemented
525
def __lt__(self, other):
526
if self._version != other._version:
527
raise TypeError('%s and %s are not of the same version' % (
529
if not isinstance(other, _BaseAddress):
530
raise TypeError('%s and %s are not of the same type' % (
532
if self._ip != other._ip:
533
return self._ip < other._ip
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)
543
def __sub__(self, other):
544
if not isinstance(other, int):
545
return NotImplemented
546
return self.__class__(int(self) - other)
549
return '%s(%r)' % (self.__class__.__name__, str(self))
552
return str(self._string_from_ip_int(self._ip))
555
return hash(hex(int(self._ip)))
557
def _get_address_key(self):
558
return (self._version, self)
561
class _BaseNetwork(_IPAddressBase):
563
"""A generic IP network object.
565
This IP class contains the version independent methods which are
569
def __init__(self, address):
573
return '%s(%r)' % (self.__class__.__name__, str(self))
576
return '%s/%d' % (self.network_address, self.prefixlen)
579
"""Generate Iterator over usable hosts in a network.
581
This is like __iter__ except it doesn't return the network
582
or broadcast addresses.
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)
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)
596
def __getitem__(self, n):
597
network = int(self.network_address)
598
broadcast = int(self.broadcast_address)
600
if network + n > broadcast:
602
return self._address_class(network + n)
605
if broadcast + n < network:
607
return self._address_class(broadcast + n)
609
def __lt__(self, other):
610
if self._version != other._version:
611
raise TypeError('%s and %s are not of the same version' % (
613
if not isinstance(other, _BaseNetwork):
614
raise TypeError('%s and %s are not of the same type' % (
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
622
def __eq__(self, other):
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
631
return hash(int(self.network_address) ^ int(self.netmask))
633
def __contains__(self, other):
634
# always false if one is v4 and the other is v6.
635
if self._version != other._version:
637
# dealing with another network.
638
if isinstance(other, _BaseNetwork):
640
# dealing with another address
643
return (int(self.network_address) <= int(other._ip) <=
644
int(self.broadcast_address))
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)))
654
def broadcast_address(self):
655
x = self._cache.get('broadcast_address')
657
x = self._address_class(int(self.network_address) |
659
self._cache['broadcast_address'] = x
664
x = self._cache.get('hostmask')
666
x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
667
self._cache['hostmask'] = x
671
def with_prefixlen(self):
672
return '%s/%d' % (self.network_address, self._prefixlen)
675
def with_netmask(self):
676
return '%s/%s' % (self.network_address, self.netmask)
679
def with_hostmask(self):
680
return '%s/%s' % (self.network_address, self.hostmask)
683
def num_addresses(self):
684
"""Number of hosts in the current subnet."""
685
return int(self.broadcast_address) - int(self.network_address) + 1
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)
697
return self._prefixlen
699
def address_exclude(self, other):
700
"""Remove an address from a larger block.
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')]
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'),
720
ip_network('2001:db8:8000::/33')]
723
other: An IPv4Network or IPv6Network object of the same type.
726
An iterator of the the IPv(4|6)Network objects which is self
730
TypeError: If self and other are of difffering address
731
versions, or if other is not a network object.
732
ValueError: If other is not completely contained by self.
735
if not self._version == other._version:
736
raise TypeError("%s and %s are not of the same version" % (
739
if not isinstance(other, _BaseNetwork):
740
raise TypeError("%s is not a network object" % other)
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))
748
# Make sure we're comparing the network of other.
749
other = other.__class__('%s/%s' % (other.network_address,
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):
757
s1, s2 = s1.subnets()
758
elif (other.network_address >= s2.network_address and
759
other.broadcast_address <= s2.broadcast_address):
761
s1, s2 = s2.subnets()
763
# If we got here, there's a bug somewhere.
764
raise AssertionError('Error performing exclusion: '
765
's1: %s s2: %s other: %s' %
772
# If we got here, there's a bug somewhere.
773
raise AssertionError('Error performing exclusion: '
774
's1: %s s2: %s other: %s' %
777
def compare_networks(self, other):
778
"""Compare two IP objects.
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'
790
If the IP versions of self and other are the same, returns:
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')
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')
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')
806
TypeError if the IP versions are different.
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' % (
813
# self._version == other._version below here:
814
if self.network_address < other.network_address:
816
if self.network_address > other.network_address:
818
# self.network_address == other.network_address below here:
819
if self.netmask < other.netmask:
821
if self.netmask > other.netmask:
825
def _get_networks_key(self):
826
"""Network-only key function.
828
Returns an object that identifies this address' network and
829
netmask. This function is a suitable "key" argument for sorted()
833
return (self._version, self.network_address, self.netmask)
835
def subnets(self, prefixlen_diff=1, new_prefix=None):
836
"""The subnets which join to make the current subnet.
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.
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.
851
An iterator of IPv(4|6) objects.
854
ValueError: The prefixlen_diff is too small or too large.
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)
861
if self._prefixlen == self._max_prefixlen:
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
872
if prefixlen_diff < 0:
873
raise ValueError('prefix length diff must be > 0')
874
new_prefixlen = self._prefixlen + prefixlen_diff
876
if not self._is_valid_netmask(str(new_prefixlen)):
878
'prefix length diff %d is invalid for netblock %s' % (
879
new_prefixlen, self))
881
first = self.__class__('%s/%s' %
882
(self.network_address,
883
self._prefixlen + prefixlen_diff))
888
broadcast = current.broadcast_address
889
if broadcast == self.broadcast_address:
891
new_addr = self._address_class(int(broadcast) + 1)
892
current = self.__class__('%s/%s' % (new_addr,
897
def supernet(self, prefixlen_diff=1, new_prefix=None):
898
"""The supernet containing the current network.
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.
907
An IPv4 network object.
910
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
911
a negative prefix length.
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
918
if self._prefixlen == 0:
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
928
if self.prefixlen - prefixlen_diff < 0:
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),
936
return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
939
def is_multicast(self):
940
"""Test if the address is reserved for multicast use.
943
A boolean, True if the address is a multicast address.
944
See RFC 2373 2.7 for details.
947
return (self.network_address.is_multicast and
948
self.broadcast_address.is_multicast)
951
def is_reserved(self):
952
"""Test if the address is otherwise IETF reserved.
955
A boolean, True if the address is within one of the
956
reserved IPv6 Network ranges.
959
return (self.network_address.is_reserved and
960
self.broadcast_address.is_reserved)
963
def is_link_local(self):
964
"""Test if the address is reserved for link-local.
967
A boolean, True if the address is reserved per RFC 4291.
970
return (self.network_address.is_link_local and
971
self.broadcast_address.is_link_local)
974
def is_private(self):
975
"""Test if this address is allocated for private networks.
978
A boolean, True if the address is reserved per RFC 4193.
981
return (self.network_address.is_private and
982
self.broadcast_address.is_private)
985
def is_unspecified(self):
986
"""Test if the address is unspecified.
989
A boolean, True if this is the unspecified address as defined in
993
return (self.network_address.is_unspecified and
994
self.broadcast_address.is_unspecified)
997
def is_loopback(self):
998
"""Test if the address is a loopback address.
1001
A boolean, True if the address is a loopback address as defined in
1005
return (self.network_address.is_loopback and
1006
self.broadcast_address.is_loopback)
1011
"""Base IPv4 object.
1013
The following methods are used by IPv4 objects in both single IP
1014
addresses and networks.
1018
# Equivalent to 255.255.255.255 or 32 bits of 1's.
1019
_ALL_ONES = (2**IPV4LENGTH) - 1
1020
_DECIMAL_DIGITS = frozenset('0123456789')
1022
# the valid octets for host and netmasks. only useful for IPv4.
1023
_valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
1025
def __init__(self, address):
1027
self._max_prefixlen = IPV4LENGTH
1029
def _explode_shorthand_ip_string(self):
1032
def _ip_int_from_string(self, ip_str):
1033
"""Turn the given IP string into an integer for comparison.
1036
ip_str: A string, the IP ip_str.
1039
The IP ip_str as an integer.
1042
AddressValueError: if ip_str isn't a valid IPv4 Address.
1046
raise AddressValueError('Address cannot be empty')
1048
octets = ip_str.split('.')
1049
if len(octets) != 4:
1050
raise AddressValueError("Expected 4 octets in %r" % ip_str)
1053
return int.from_bytes(map(self._parse_octet, octets), 'big')
1054
except ValueError as exc:
1055
raise AddressValueError("%s in %r" % (exc, ip_str))
1057
def _parse_octet(self, octet_str):
1058
"""Convert a decimal octet into an integer.
1061
octet_str: A string, the number to parse.
1064
The octet as an integer.
1067
ValueError: if the octet isn't strictly a decimal from [0..255].
1071
raise ValueError("Empty octet not permitted")
1072
# Whitelist the characters, since int() allows a lot of bizarre stuff.
1073
if not self._DECIMAL_DIGITS.issuperset(octet_str):
1074
msg = "Only decimal digits permitted in %r"
1075
raise ValueError(msg % octet_str)
1076
# We do the length check second, since the invalid character error
1077
# is likely to be more informative for the user
1078
if len(octet_str) > 3:
1079
msg = "At most 3 characters permitted in %r"
1080
raise ValueError(msg % octet_str)
1081
# Convert to integer (we know digits are legal)
1082
octet_int = int(octet_str, 10)
1083
# Any octets that look like they *might* be written in octal,
1084
# and which don't look exactly the same in both octal and
1085
# decimal are rejected as ambiguous
1086
if octet_int > 7 and octet_str[0] == '0':
1087
msg = "Ambiguous (octal/decimal) value in %r not permitted"
1088
raise ValueError(msg % octet_str)
1090
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
1093
def _string_from_ip_int(self, ip_int):
1094
"""Turns a 32-bit integer into dotted decimal notation.
1097
ip_int: An integer, the IP address.
1100
The IP address as a string in dotted decimal notation.
1103
return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
1105
def _is_valid_netmask(self, netmask):
1106
"""Verify that the netmask is valid.
1109
netmask: A string, either a prefix or dotted decimal
1113
A boolean, True if the prefix represents a valid IPv4
1117
mask = netmask.split('.')
1121
if int(x) not in self._valid_mask_octets:
1124
# Found something that isn't an integer or isn't valid
1126
for idx, y in enumerate(mask):
1127
if idx > 0 and y > mask[idx - 1]:
1131
netmask = int(netmask)
1134
return 0 <= netmask <= self._max_prefixlen
1136
def _is_hostmask(self, ip_str):
1137
"""Test if the IP string is a hostmask (rather than a netmask).
1140
ip_str: A string, the potential hostmask.
1143
A boolean, True if the IP string is a hostmask.
1146
bits = ip_str.split('.')
1148
parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
1151
if len(parts) != len(bits):
1153
if parts[0] < parts[-1]:
1158
def max_prefixlen(self):
1159
return self._max_prefixlen
1163
return self._version
1166
class IPv4Address(_BaseV4, _BaseAddress):
1168
"""Represent and manipulate single IPv4 Addresses."""
1170
def __init__(self, address):
1174
address: A string or integer representing the IP
1176
Additionally, an integer can be passed, so
1177
IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1179
IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1180
IPv4Address('192.0.2.1')
1183
AddressValueError: If ipaddress isn't a valid IPv4 address.
1186
_BaseAddress.__init__(self, address)
1187
_BaseV4.__init__(self, address)
1189
# Efficient constructor from integer.
1190
if isinstance(address, int):
1191
self._check_int_address(address)
1195
# Constructing from a packed address
1196
if isinstance(address, bytes):
1197
self._check_packed_address(address, 4)
1198
self._ip = int.from_bytes(address, 'big')
1201
# Assume input argument to be string or any object representation
1202
# which converts into a formatted IP string.
1203
addr_str = str(address)
1204
self._ip = self._ip_int_from_string(addr_str)
1208
"""The binary representation of this address."""
1209
return v4_int_to_packed(self._ip)
1212
def is_reserved(self):
1213
"""Test if the address is otherwise IETF reserved.
1216
A boolean, True if the address is within the
1217
reserved IPv4 Network range.
1220
reserved_network = IPv4Network('240.0.0.0/4')
1221
return self in reserved_network
1224
def is_private(self):
1225
"""Test if this address is allocated for private networks.
1228
A boolean, True if the address is reserved per RFC 1918.
1231
private_10 = IPv4Network('10.0.0.0/8')
1232
private_172 = IPv4Network('172.16.0.0/12')
1233
private_192 = IPv4Network('192.168.0.0/16')
1234
return (self in private_10 or
1235
self in private_172 or
1236
self in private_192)
1239
def is_multicast(self):
1240
"""Test if the address is reserved for multicast use.
1243
A boolean, True if the address is multicast.
1244
See RFC 3171 for details.
1247
multicast_network = IPv4Network('224.0.0.0/4')
1248
return self in multicast_network
1251
def is_unspecified(self):
1252
"""Test if the address is unspecified.
1255
A boolean, True if this is the unspecified address as defined in
1259
unspecified_address = IPv4Address('0.0.0.0')
1260
return self == unspecified_address
1263
def is_loopback(self):
1264
"""Test if the address is a loopback address.
1267
A boolean, True if the address is a loopback per RFC 3330.
1270
loopback_network = IPv4Network('127.0.0.0/8')
1271
return self in loopback_network
1274
def is_link_local(self):
1275
"""Test if the address is reserved for link-local.
1278
A boolean, True if the address is link-local per RFC 3927.
1281
linklocal_network = IPv4Network('169.254.0.0/16')
1282
return self in linklocal_network
1285
class IPv4Interface(IPv4Address):
1287
def __init__(self, address):
1288
if isinstance(address, (bytes, int)):
1289
IPv4Address.__init__(self, address)
1290
self.network = IPv4Network(self._ip)
1291
self._prefixlen = self._max_prefixlen
1294
addr = _split_optional_netmask(address)
1295
IPv4Address.__init__(self, addr[0])
1297
self.network = IPv4Network(address, strict=False)
1298
self._prefixlen = self.network._prefixlen
1300
self.netmask = self.network.netmask
1301
self.hostmask = self.network.hostmask
1304
return '%s/%d' % (self._string_from_ip_int(self._ip),
1305
self.network.prefixlen)
1307
def __eq__(self, other):
1308
address_equal = IPv4Address.__eq__(self, other)
1309
if not address_equal or address_equal is NotImplemented:
1310
return address_equal
1312
return self.network == other.network
1313
except AttributeError:
1314
# An interface with an associated network is NOT the
1315
# same as an unassociated address. That's why the hash
1316
# takes the extra info into account.
1319
def __lt__(self, other):
1320
address_less = IPv4Address.__lt__(self, other)
1321
if address_less is NotImplemented:
1322
return NotImplemented
1324
return self.network < other.network
1325
except AttributeError:
1326
# We *do* allow addresses and interfaces to be sorted. The
1327
# unassociated address is considered less than all interfaces.
1331
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1335
return IPv4Address(self._ip)
1338
def with_prefixlen(self):
1339
return '%s/%s' % (self._string_from_ip_int(self._ip),
1343
def with_netmask(self):
1344
return '%s/%s' % (self._string_from_ip_int(self._ip),
1348
def with_hostmask(self):
1349
return '%s/%s' % (self._string_from_ip_int(self._ip),
1353
class IPv4Network(_BaseV4, _BaseNetwork):
1355
"""This class represents and manipulates 32-bit IPv4 network + addresses..
1357
Attributes: [examples for IPv4Network('192.0.2.0/27')]
1358
.network_address: IPv4Address('192.0.2.0')
1359
.hostmask: IPv4Address('0.0.0.31')
1360
.broadcast_address: IPv4Address('192.0.2.32')
1361
.netmask: IPv4Address('255.255.255.224')
1365
# Class to use when creating address objects
1366
_address_class = IPv4Address
1368
def __init__(self, address, strict=True):
1370
"""Instantiate a new IPv4 network object.
1373
address: A string or integer representing the IP [& network].
1375
'192.0.2.0/255.255.255.0'
1376
'192.0.0.2/0.0.0.255'
1377
are all functionally the same in IPv4. Similarly,
1379
'192.0.2.1/255.255.255.255'
1381
are also functionaly equivalent. That is to say, failing to
1382
provide a subnetmask will create an object with a mask of /32.
1384
If the mask (portion after the / in the argument) is given in
1385
dotted quad form, it is treated as a netmask if it starts with a
1386
non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1387
starts with a zero field (e.g. 0.255.255.255 == /8), with the
1388
single exception of an all-zero mask which is treated as a
1389
netmask == /0. If no mask is given, a default of /32 is used.
1391
Additionally, an integer can be passed, so
1392
IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1394
IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1395
IPv4Interface('192.0.2.1')
1398
AddressValueError: If ipaddress isn't a valid IPv4 address.
1399
NetmaskValueError: If the netmask isn't valid for
1401
ValueError: If strict is True and a network address is not
1406
_BaseV4.__init__(self, address)
1407
_BaseNetwork.__init__(self, address)
1409
# Constructing from a packed address
1410
if isinstance(address, bytes):
1411
self.network_address = IPv4Address(address)
1412
self._prefixlen = self._max_prefixlen
1413
self.netmask = IPv4Address(self._ALL_ONES)
1414
#fixme: address/network test here
1417
# Efficient constructor from integer.
1418
if isinstance(address, int):
1419
self.network_address = IPv4Address(address)
1420
self._prefixlen = self._max_prefixlen
1421
self.netmask = IPv4Address(self._ALL_ONES)
1422
#fixme: address/network test here.
1425
# Assume input argument to be string or any object representation
1426
# which converts into a formatted IP prefix string.
1427
addr = _split_optional_netmask(address)
1428
self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1431
mask = addr[1].split('.')
1434
# We have dotted decimal netmask.
1435
if self._is_valid_netmask(addr[1]):
1436
self.netmask = IPv4Address(self._ip_int_from_string(
1438
elif self._is_hostmask(addr[1]):
1439
self.netmask = IPv4Address(
1440
self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1442
raise NetmaskValueError('%r is not a valid netmask'
1445
self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1447
# We have a netmask in prefix length form.
1448
if not self._is_valid_netmask(addr[1]):
1449
raise NetmaskValueError('%r is not a valid netmask'
1451
self._prefixlen = int(addr[1])
1452
self.netmask = IPv4Address(self._ip_int_from_prefix(
1455
self._prefixlen = self._max_prefixlen
1456
self.netmask = IPv4Address(self._ip_int_from_prefix(
1460
if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1461
self.network_address):
1462
raise ValueError('%s has host bits set' % self)
1463
self.network_address = IPv4Address(int(self.network_address) &
1466
if self._prefixlen == (self._max_prefixlen - 1):
1467
self.hosts = self.__iter__
1472
"""Base IPv6 object.
1474
The following methods are used by IPv6 objects in both single IP
1475
addresses and networks.
1479
_ALL_ONES = (2**IPV6LENGTH) - 1
1481
_HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1483
def __init__(self, address):
1485
self._max_prefixlen = IPV6LENGTH
1487
def _ip_int_from_string(self, ip_str):
1488
"""Turn an IPv6 ip_str into an integer.
1491
ip_str: A string, the IPv6 ip_str.
1494
An int, the IPv6 address
1497
AddressValueError: if ip_str isn't a valid IPv6 Address.
1501
raise AddressValueError('Address cannot be empty')
1503
parts = ip_str.split(':')
1505
# An IPv6 address needs at least 2 colons (3 parts).
1507
if len(parts) < _min_parts:
1508
msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1509
raise AddressValueError(msg)
1511
# If the address has an IPv4-style suffix, convert it to hexadecimal.
1512
if '.' in parts[-1]:
1514
ipv4_int = IPv4Address(parts.pop())._ip
1515
except AddressValueError as exc:
1516
raise AddressValueError("%s in %r" % (exc, ip_str))
1517
parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1518
parts.append('%x' % (ipv4_int & 0xFFFF))
1520
# An IPv6 address can't have more than 8 colons (9 parts).
1521
# The extra colon comes from using the "::" notation for a single
1522
# leading or trailing zero part.
1523
_max_parts = self._HEXTET_COUNT + 1
1524
if len(parts) > _max_parts:
1525
msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1526
raise AddressValueError(msg)
1528
# Disregarding the endpoints, find '::' with nothing in between.
1529
# This indicates that a run of zeroes has been skipped.
1531
for i in range(1, len(parts) - 1):
1533
if skip_index is not None:
1534
# Can't have more than one '::'
1535
msg = "At most one '::' permitted in %r" % ip_str
1536
raise AddressValueError(msg)
1539
# parts_hi is the number of parts to copy from above/before the '::'
1540
# parts_lo is the number of parts to copy from below/after the '::'
1541
if skip_index is not None:
1542
# If we found a '::', then check if it also covers the endpoints.
1543
parts_hi = skip_index
1544
parts_lo = len(parts) - skip_index - 1
1548
msg = "Leading ':' only permitted as part of '::' in %r"
1549
raise AddressValueError(msg % ip_str) # ^: requires ^::
1553
msg = "Trailing ':' only permitted as part of '::' in %r"
1554
raise AddressValueError(msg % ip_str) # :$ requires ::$
1555
parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1556
if parts_skipped < 1:
1557
msg = "Expected at most %d other parts with '::' in %r"
1558
raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
1560
# Otherwise, allocate the entire address to parts_hi. The
1561
# endpoints could still be empty, but _parse_hextet() will check
1563
if len(parts) != self._HEXTET_COUNT:
1564
msg = "Exactly %d parts expected without '::' in %r"
1565
raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1567
msg = "Leading ':' only permitted as part of '::' in %r"
1568
raise AddressValueError(msg % ip_str) # ^: requires ^::
1570
msg = "Trailing ':' only permitted as part of '::' in %r"
1571
raise AddressValueError(msg % ip_str) # :$ requires ::$
1572
parts_hi = len(parts)
1577
# Now, parse the hextets into a 128-bit integer.
1579
for i in range(parts_hi):
1581
ip_int |= self._parse_hextet(parts[i])
1582
ip_int <<= 16 * parts_skipped
1583
for i in range(-parts_lo, 0):
1585
ip_int |= self._parse_hextet(parts[i])
1587
except ValueError as exc:
1588
raise AddressValueError("%s in %r" % (exc, ip_str))
1590
def _parse_hextet(self, hextet_str):
1591
"""Convert an IPv6 hextet string into an integer.
1594
hextet_str: A string, the number to parse.
1597
The hextet as an integer.
1600
ValueError: if the input isn't strictly a hex number from
1604
# Whitelist the characters, since int() allows a lot of bizarre stuff.
1605
if not self._HEX_DIGITS.issuperset(hextet_str):
1606
raise ValueError("Only hex digits permitted in %r" % hextet_str)
1607
# We do the length check second, since the invalid character error
1608
# is likely to be more informative for the user
1609
if len(hextet_str) > 4:
1610
msg = "At most 4 characters permitted in %r"
1611
raise ValueError(msg % hextet_str)
1612
# Length check means we can skip checking the integer value
1613
return int(hextet_str, 16)
1615
def _compress_hextets(self, hextets):
1616
"""Compresses a list of hextets.
1618
Compresses a list of strings, replacing the longest continuous
1619
sequence of "0" in the list with "" and adding empty strings at
1620
the beginning or at the end of the string such that subsequently
1621
calling ":".join(hextets) will produce the compressed version of
1625
hextets: A list of strings, the hextets to compress.
1631
best_doublecolon_start = -1
1632
best_doublecolon_len = 0
1633
doublecolon_start = -1
1635
for index, hextet in enumerate(hextets):
1637
doublecolon_len += 1
1638
if doublecolon_start == -1:
1639
# Start of a sequence of zeros.
1640
doublecolon_start = index
1641
if doublecolon_len > best_doublecolon_len:
1642
# This is the longest sequence of zeros so far.
1643
best_doublecolon_len = doublecolon_len
1644
best_doublecolon_start = doublecolon_start
1647
doublecolon_start = -1
1649
if best_doublecolon_len > 1:
1650
best_doublecolon_end = (best_doublecolon_start +
1651
best_doublecolon_len)
1652
# For zeros at the end of the address.
1653
if best_doublecolon_end == len(hextets):
1655
hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1656
# For zeros at the beginning of the address.
1657
if best_doublecolon_start == 0:
1658
hextets = [''] + hextets
1662
def _string_from_ip_int(self, ip_int=None):
1663
"""Turns a 128-bit integer into hexadecimal notation.
1666
ip_int: An integer, the IP address.
1669
A string, the hexadecimal representation of the address.
1672
ValueError: The address is bigger than 128 bits of all ones.
1676
ip_int = int(self._ip)
1678
if ip_int > self._ALL_ONES:
1679
raise ValueError('IPv6 address is too large')
1681
hex_str = '%032x' % ip_int
1682
hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
1684
hextets = self._compress_hextets(hextets)
1685
return ':'.join(hextets)
1687
def _explode_shorthand_ip_string(self):
1688
"""Expand a shortened IPv6 address.
1691
ip_str: A string, the IPv6 address.
1694
A string, the expanded IPv6 address.
1697
if isinstance(self, IPv6Network):
1698
ip_str = str(self.network_address)
1699
elif isinstance(self, IPv6Interface):
1700
ip_str = str(self.ip)
1704
ip_int = self._ip_int_from_string(ip_str)
1705
hex_str = '%032x' % ip_int
1706
parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
1707
if isinstance(self, (_BaseNetwork, IPv6Interface)):
1708
return '%s/%d' % (':'.join(parts), self._prefixlen)
1709
return ':'.join(parts)
1712
def max_prefixlen(self):
1713
return self._max_prefixlen
1717
return self._version
1720
class IPv6Address(_BaseV6, _BaseAddress):
1722
"""Represent and manipulate single IPv6 Addresses."""
1724
def __init__(self, address):
1725
"""Instantiate a new IPv6 address object.
1728
address: A string or integer representing the IP
1730
Additionally, an integer can be passed, so
1731
IPv6Address('2001:db8::') ==
1732
IPv6Address(42540766411282592856903984951653826560)
1734
IPv6Address(int(IPv6Address('2001:db8::'))) ==
1735
IPv6Address('2001:db8::')
1738
AddressValueError: If address isn't a valid IPv6 address.
1741
_BaseAddress.__init__(self, address)
1742
_BaseV6.__init__(self, address)
1744
# Efficient constructor from integer.
1745
if isinstance(address, int):
1746
self._check_int_address(address)
1750
# Constructing from a packed address
1751
if isinstance(address, bytes):
1752
self._check_packed_address(address, 16)
1753
self._ip = int.from_bytes(address, 'big')
1756
# Assume input argument to be string or any object representation
1757
# which converts into a formatted IP string.
1758
addr_str = str(address)
1759
self._ip = self._ip_int_from_string(addr_str)
1763
"""The binary representation of this address."""
1764
return v6_int_to_packed(self._ip)
1767
def is_multicast(self):
1768
"""Test if the address is reserved for multicast use.
1771
A boolean, True if the address is a multicast address.
1772
See RFC 2373 2.7 for details.
1775
multicast_network = IPv6Network('ff00::/8')
1776
return self in multicast_network
1779
def is_reserved(self):
1780
"""Test if the address is otherwise IETF reserved.
1783
A boolean, True if the address is within one of the
1784
reserved IPv6 Network ranges.
1787
reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1788
IPv6Network('200::/7'), IPv6Network('400::/6'),
1789
IPv6Network('800::/5'), IPv6Network('1000::/4'),
1790
IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1791
IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1792
IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1793
IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1794
IPv6Network('FE00::/9')]
1796
return any(self in x for x in reserved_networks)
1799
def is_link_local(self):
1800
"""Test if the address is reserved for link-local.
1803
A boolean, True if the address is reserved per RFC 4291.
1806
linklocal_network = IPv6Network('fe80::/10')
1807
return self in linklocal_network
1810
def is_site_local(self):
1811
"""Test if the address is reserved for site-local.
1813
Note that the site-local address space has been deprecated by RFC 3879.
1814
Use is_private to test if this address is in the space of unique local
1815
addresses as defined by RFC 4193.
1818
A boolean, True if the address is reserved per RFC 3513 2.5.6.
1821
sitelocal_network = IPv6Network('fec0::/10')
1822
return self in sitelocal_network
1825
def is_private(self):
1826
"""Test if this address is allocated for private networks.
1829
A boolean, True if the address is reserved per RFC 4193.
1832
private_network = IPv6Network('fc00::/7')
1833
return self in private_network
1836
def is_unspecified(self):
1837
"""Test if the address is unspecified.
1840
A boolean, True if this is the unspecified address as defined in
1844
return self._ip == 0
1847
def is_loopback(self):
1848
"""Test if the address is a loopback address.
1851
A boolean, True if the address is a loopback address as defined in
1855
return self._ip == 1
1858
def ipv4_mapped(self):
1859
"""Return the IPv4 mapped address.
1862
If the IPv6 address is a v4 mapped address, return the
1863
IPv4 mapped address. Return None otherwise.
1866
if (self._ip >> 32) != 0xFFFF:
1868
return IPv4Address(self._ip & 0xFFFFFFFF)
1872
"""Tuple of embedded teredo IPs.
1875
Tuple of the (server, client) IPs or None if the address
1876
doesn't appear to be a teredo address (doesn't start with
1880
if (self._ip >> 96) != 0x20010000:
1882
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1883
IPv4Address(~self._ip & 0xFFFFFFFF))
1886
def sixtofour(self):
1887
"""Return the IPv4 6to4 embedded address.
1890
The IPv4 6to4-embedded address if present or None if the
1891
address doesn't appear to contain a 6to4 embedded address.
1894
if (self._ip >> 112) != 0x2002:
1896
return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1899
class IPv6Interface(IPv6Address):
1901
def __init__(self, address):
1902
if isinstance(address, (bytes, int)):
1903
IPv6Address.__init__(self, address)
1904
self.network = IPv6Network(self._ip)
1905
self._prefixlen = self._max_prefixlen
1908
addr = _split_optional_netmask(address)
1909
IPv6Address.__init__(self, addr[0])
1910
self.network = IPv6Network(address, strict=False)
1911
self.netmask = self.network.netmask
1912
self._prefixlen = self.network._prefixlen
1913
self.hostmask = self.network.hostmask
1916
return '%s/%d' % (self._string_from_ip_int(self._ip),
1917
self.network.prefixlen)
1919
def __eq__(self, other):
1920
address_equal = IPv6Address.__eq__(self, other)
1921
if not address_equal or address_equal is NotImplemented:
1922
return address_equal
1924
return self.network == other.network
1925
except AttributeError:
1926
# An interface with an associated network is NOT the
1927
# same as an unassociated address. That's why the hash
1928
# takes the extra info into account.
1931
def __lt__(self, other):
1932
address_less = IPv6Address.__lt__(self, other)
1933
if address_less is NotImplemented:
1934
return NotImplemented
1936
return self.network < other.network
1937
except AttributeError:
1938
# We *do* allow addresses and interfaces to be sorted. The
1939
# unassociated address is considered less than all interfaces.
1943
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1947
return IPv6Address(self._ip)
1950
def with_prefixlen(self):
1951
return '%s/%s' % (self._string_from_ip_int(self._ip),
1955
def with_netmask(self):
1956
return '%s/%s' % (self._string_from_ip_int(self._ip),
1960
def with_hostmask(self):
1961
return '%s/%s' % (self._string_from_ip_int(self._ip),
1965
def is_unspecified(self):
1966
return self._ip == 0 and self.network.is_unspecified
1969
def is_loopback(self):
1970
return self._ip == 1 and self.network.is_loopback
1973
class IPv6Network(_BaseV6, _BaseNetwork):
1975
"""This class represents and manipulates 128-bit IPv6 networks.
1977
Attributes: [examples for IPv6('2001:db8::1000/124')]
1978
.network_address: IPv6Address('2001:db8::1000')
1979
.hostmask: IPv6Address('::f')
1980
.broadcast_address: IPv6Address('2001:db8::100f')
1981
.netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1986
# Class to use when creating address objects
1987
_address_class = IPv6Address
1989
def __init__(self, address, strict=True):
1990
"""Instantiate a new IPv6 Network object.
1993
address: A string or integer representing the IPv6 network or the
1994
IP and prefix/netmask.
1996
'2001:db8:0000:0000:0000:0000:0000:0000/128'
1998
are all functionally the same in IPv6. That is to say,
1999
failing to provide a subnetmask will create an object with
2002
Additionally, an integer can be passed, so
2003
IPv6Network('2001:db8::') ==
2004
IPv6Network(42540766411282592856903984951653826560)
2006
IPv6Network(int(IPv6Network('2001:db8::'))) ==
2007
IPv6Network('2001:db8::')
2009
strict: A boolean. If true, ensure that we have been passed
2010
A true network address, eg, 2001:db8::1000/124 and not an
2011
IP address on a network, eg, 2001:db8::1/124.
2014
AddressValueError: If address isn't a valid IPv6 address.
2015
NetmaskValueError: If the netmask isn't valid for
2017
ValueError: If strict was True and a network address was not
2021
_BaseV6.__init__(self, address)
2022
_BaseNetwork.__init__(self, address)
2024
# Efficient constructor from integer.
2025
if isinstance(address, int):
2026
self.network_address = IPv6Address(address)
2027
self._prefixlen = self._max_prefixlen
2028
self.netmask = IPv6Address(self._ALL_ONES)
2031
# Constructing from a packed address
2032
if isinstance(address, bytes):
2033
self.network_address = IPv6Address(address)
2034
self._prefixlen = self._max_prefixlen
2035
self.netmask = IPv6Address(self._ALL_ONES)
2038
# Assume input argument to be string or any object representation
2039
# which converts into a formatted IP prefix string.
2040
addr = _split_optional_netmask(address)
2042
self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2045
if self._is_valid_netmask(addr[1]):
2046
self._prefixlen = int(addr[1])
2048
raise NetmaskValueError('%r is not a valid netmask'
2051
self._prefixlen = self._max_prefixlen
2053
self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2055
if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2056
self.network_address):
2057
raise ValueError('%s has host bits set' % self)
2058
self.network_address = IPv6Address(int(self.network_address) &
2061
if self._prefixlen == (self._max_prefixlen - 1):
2062
self.hosts = self.__iter__
2064
def _is_valid_netmask(self, prefixlen):
2065
"""Verify that the netmask/prefixlen is valid.
2068
prefixlen: A string, the netmask in prefix length format.
2071
A boolean, True if the prefix represents a valid IPv6
2076
prefixlen = int(prefixlen)
2079
return 0 <= prefixlen <= self._max_prefixlen
2082
def is_site_local(self):
2083
"""Test if the address is reserved for site-local.
2085
Note that the site-local address space has been deprecated by RFC 3879.
2086
Use is_private to test if this address is in the space of unique local
2087
addresses as defined by RFC 4193.
2090
A boolean, True if the address is reserved per RFC 3513 2.5.6.
2093
return (self.network_address.is_site_local and
2094
self.broadcast_address.is_site_local)