This file is indexed.

/usr/share/pyshared/netaddr/ip/__init__.py is in python-netaddr 0.7.5-4build2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
#-----------------------------------------------------------------------------
#   Copyright (c) 2008-2010, David P. D. Moss. All rights reserved.
#
#   Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
"""Routines for IPv4 and IPv6 addresses, subnets and ranges."""

import sys as _sys
import re as _re

from netaddr.core import AddrFormatError, AddrConversionError, num_bits, \
    DictDotLookup, NOHOST, N, INET_PTON, P, ZEROFILL, Z

from netaddr.strategy import ipv4 as _ipv4, ipv6 as _ipv6

from netaddr.compat import _sys_maxint, _iter_range, _is_str, _int_type, \
    _str_type

#-----------------------------------------------------------------------------
#   Pre-compiled regexen used by cidr_merge() function.
RE_CIDR_ADJACENT = _re.compile(r'^([01]+)0 \1[1]$')
RE_CIDR_WITHIN = _re.compile(r'^([01]+) \1[10]+$')
RE_VALID_CIDR_BITS = _re.compile('^[01]+$')

#-----------------------------------------------------------------------------
class BaseIP(object):
    """
    An abstract base class for common operations shared between various IP
    related subclasses.

    """
    __slots__ = ('_value', '_module')

    def __init__(self):
        """Constructor."""
        self._value = None
        self._module = None

    def _set_value(self, value):
        if not isinstance(value, _int_type):
            raise TypeError('int argument expected, not %s' % type(value))
        if not 0 <= value <= self._module.max_int:
            raise AddrFormatError('value out of bounds for an %s address!' \
                % self._module.family_name)
        self._value = value

    value = property(lambda self: self._value, _set_value,
        doc='a positive integer representing the value of IP address/subnet.')

    def key(self):
        """
        @return: a key tuple that uniquely identifies this IP address.
        """
        return NotImplemented

    def sort_key(self):
        """
        @return: A key tuple used to compare and sort this L{IPAddress}
            correctly.
        """
        return NotImplemented

    def __hash__(self):
        """
        @return: A hash value uniquely indentifying this IP object.
        """
        return hash(self.key())

    def __eq__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            equivalent to C{other}, C{False} otherwise.
        """
        try:
            return self.key() == other.key()
        except AttributeError:
            return NotImplemented

    def __ne__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            not equivalent to C{other}, C{False} otherwise.
        """
        try:
            return self.key() != other.key()
        except AttributeError:
            return NotImplemented

    def __lt__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            less than C{other}, C{False} otherwise.
        """
        try:
            return self.sort_key() < other.sort_key()
        except AttributeError:
            return NotImplemented

    def __le__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            less than or equal to C{other}, C{False} otherwise.
        """
        try:
            return self.sort_key() <= other.sort_key()
        except AttributeError:
            return NotImplemented

    def __gt__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            greater than C{other}, C{False} otherwise.
        """
        try:
            return self.sort_key() > other.sort_key()
        except AttributeError:
            return NotImplemented

    def __ge__(self, other):
        """
        @param other: an L{IPAddress} or L{IPNetwork} object.

        @return: C{True} if this L{IPAddress} or L{IPNetwork} object is
            greater than or equal to C{other}, C{False} otherwise.
        """
        try:
            return self.sort_key() >= other.sort_key()
        except AttributeError:
            return NotImplemented

    def is_unicast(self):
        """@return: C{True} if this IP is unicast, C{False} otherwise"""
        return not self.is_multicast()

    def is_multicast(self):
        """@return: C{True} if this IP is multicast, C{False} otherwise"""
        if self._module == _ipv4:
            return self in IPV4_MULTICAST
        elif self._module == _ipv6:
            return self in IPV6_MULTICAST

    def is_loopback(self):
        """
        @return: C{True} if this IP is loopback address (not for network
            transmission), C{False} otherwise.
            References: RFC 3330 and 4291.
        """
        if self.version == 4:
            return self in IPV4_LOOPBACK
        elif self.version == 6:
            return self == IPV6_LOOPBACK

    def is_private(self):
        """
        @return: C{True} if this IP is for internal/private use only
            (i.e. non-public), C{False} otherwise. Reference: RFCs 1918,
            3330, 4193, 3879 and 2365.
        """
        if self.version == 4:
            for cidr in IPV4_PRIVATE:
                if self in cidr:
                    return True
        elif self.version == 6:
            for cidr in IPV6_PRIVATE:
                if self in cidr:
                    return True

        if self.is_link_local():
            return True

        return False

    def is_link_local(self):
        """
        @return: C{True} if this IP is link-local address C{False} otherwise.
            Reference: RFCs 3927 and 4291.
        """
        if self.version == 4:
            return self in IPV4_LINK_LOCAL
        elif self.version == 6:
            return self in IPV6_LINK_LOCAL

    def is_reserved(self):
        """
        @return: C{True} if this IP is in IANA reserved range, C{False}
            otherwise. Reference: RFCs 3330 and 3171.
        """
        if self.version == 4:
            for cidr in IPV4_RESERVED:
                if self in cidr:
                    return True
        elif self.version == 6:
            for cidr in IPV6_RESERVED:
                if self in cidr:
                    return True
        return False

    def is_ipv4_mapped(self):
        """
        @return: C{True} if this IP is IPv4-compatible IPv6 address, C{False}
            otherwise.
        """
        return self.version == 6 and (self._value >> 32) == 0xffff

    def is_ipv4_compat(self):
        """
        @return: C{True} if this IP is IPv4-mapped IPv6 address, C{False}
            otherwise.
        """
        return self.version == 6 and (self._value >> 32) == 0

    @property
    def info(self):
        """
        A record dict containing IANA registration details for this IP address
        if available, None otherwise.
        """
        #   Lazy loading of IANA data structures.
        from netaddr.ip.iana import query
        return DictDotLookup(query(self))

    @property
    def version(self):
        """the IP protocol version represented by this IP object."""
        return self._module.version


#-----------------------------------------------------------------------------
class IPAddress(BaseIP):
    """
    An individual IPv4 or IPv6 address without a net mask or subnet prefix.

    To support these and other network based operations, see L{IPNetwork}.

    """
    __slots__ = ()

    def __init__(self, addr, version=None, flags=0):
        """
        Constructor.

        @param addr: an IPv4 or IPv6 address which may be represented in an
            accepted string format, as an unsigned integer or as another
            IPAddress object (copy construction).

        @param version: (optional) optimizes version detection if specified
            and distinguishes between IPv4 and IPv6 for addresses with an
            equivalent integer value.

        @param flags: (optional) decides which rules are applied to the
            interpretation of the addr value. Supported constants are
            INET_PTON and ZEROFILL. See the netaddr.core docs for further
            details.

        """
        super(IPAddress, self).__init__()

        if isinstance(addr, BaseIP):
            #   Copy constructor.
            if version is not None and version != addr._module.version:
                raise ValueError('cannot switch IP versions using '
                    'copy constructor!')
            self._value = addr._value
            self._module = addr._module
        else:
            #   Explicit IP address version.
            if version is not None:
                if version == 4:
                    self._module = _ipv4
                elif version == 6:
                    self._module = _ipv6
                else:
                    raise ValueError('%r is an invalid IP version!' % version)

            has_upper = hasattr(addr, 'upper')
            if has_upper and '/' in addr:
                raise ValueError('%s() does not support netmasks or subnet' \
                    ' prefixes! See documentation for details.'
                    % self.__class__.__name__)

            if self._module is None:
                #   IP version is implicit, detect it from addr.
                if isinstance(addr, _int_type):
                    try:
                        if 0 <= int(addr) <= _ipv4.max_int:
                            self._value = int(addr)
                            self._module = _ipv4
                        elif _ipv4.max_int < int(addr) <= _ipv6.max_int:
                            self._value = int(addr)
                            self._module = _ipv6
                    except ValueError:
                        pass
                else:
                    for module in _ipv4, _ipv6:
                        try:
                            self._value = module.str_to_int(addr, flags)
                        except:
                            continue
                        else:
                            self._module = module
                            break

                if self._module is None:
                    raise AddrFormatError('failed to detect a valid IP ' \
                        'address from %r' % addr)
            else:
                #   IP version is explicit.
                if has_upper:
                    try:
                        self._value = self._module.str_to_int(addr, flags)
                    except AddrFormatError:
                        raise AddrFormatError('base address %r is not IPv%d'
                            % (addr, self._module.version))
                else:
                    if 0 <= int(addr) <= self._module.max_int:
                        self._value = int(addr)
                    else:
                        raise AddrFormatError('bad address format: %r' % addr)

    def __getstate__(self):
        """@return: Pickled state of an C{IPAddress} object."""
        return self._value, self._module.version

    def __setstate__(self, state):
        """
        @param state: data used to unpickle a pickled C{IPAddress} object.

        """
        value, version = state

        self._value = value

        if version == 4:
            self._module = _ipv4
        elif version == 6:
            self._module = _ipv6
        else:
            raise ValueError('unpickling failed for object state: %s' \
                % str(state))

    def is_hostmask(self):
        """
        @return: C{True} if this IP address host mask, C{False} otherwise.
        """
        int_val = self._value + 1
        return (int_val & (int_val - 1) == 0)

    def is_netmask(self):
        """
        @return: C{True} if this IP address network mask, C{False} otherwise.
        """
        int_val = (self._value ^ self._module.max_int) + 1
        return (int_val & (int_val - 1) == 0)

    def __iadd__(self, num):
        """
        Increases the numerical value of this IPAddress by num.

        @param num: size of IP address increment.

        An IndexError is raised if result exceeds maximum IP address value or
        is less than zero.
        """
        new_value = self._value + num
        if 0 <= new_value <= self._module.max_int:
            self._value = new_value
            return self
        raise IndexError('result outside valid IP address boundary!')

    def __isub__(self, num):
        """
        Decreases the numerical value of this IPAddress by num.

        @param num: size of IP address decrement.

        An IndexError is raised if result is less than zero or exceeds maximum
        IP address value.
        """
        new_value = self._value - num
        if 0 <= new_value <= self._module.max_int:
            self._value = new_value
            return self
        raise IndexError('result outside valid IP address boundary!')

    def __add__(self, num):
        """
        Add the numerical value of this IP address to num and provide the
        result as a new IPAddress object.

        @param num: size of IP address increase.

        @return: a new IPAddress object with its numerical value increased by
        num.
        """
        new_value = self._value + num
        if 0 <= new_value <= self._module.max_int:
            return self.__class__(new_value, self.version)
        raise IndexError('result outside valid IP address boundary!')

    __radd__ = __add__

    def __sub__(self, num):
        """
        Subtract the numerical value of this IP address from num providing
        the result as a new IPAddress object.

        @param num: size of IP address decrease.

        @return: a new IPAddress object with its numerical value decreased by
        num.
        """
        new_value = self._value - num
        if 0 <= new_value <= self._module.max_int:
            return self.__class__(new_value, self.version)
        raise IndexError('result outside valid IP address boundary!')

    def __rsub__(self, num):
        """
        Subtract num (lvalue) from the numerical value of this IP address (rvalue) providing the result as a new IPAddress object.

        @param num: size of IP address decrease.

        @return: a new IPAddress object with its numerical value decreased by
        num.
        """
        new_value = num - self._value
        if 0 <= new_value <= self._module.max_int:
            return self.__class__(new_value, self.version)
        raise IndexError('result outside valid IP address boundary!')

    def key(self):
        """
        @return: a key tuple that uniquely identifies this IP address.
        """
        #   NB - we return the value here twice because this IP Address may
        #   be sorted with a list of networks and it should still end up
        #   in the expected order.
        return self.version, self._value

    def sort_key(self):
        """
        @return: A key tuple used to compare and sort this L{IPAddress}
            correctly.
        """
        return self.version, self._value, self._module.width

    def __int__(self):
        """@return: the value of this IP address as an unsigned integer"""
        return self._value

    def __long__(self):
        """@return: the value of this IP address as an unsigned integer"""
        return self._value

    def __oct__(self):
        """@return: an octal string representation of this IP address."""
        #   Python 2.x
        if self._value == 0:
            return '0'
        return '0%o' % self._value

    def __hex__(self):
        """@return: a hexadecimal string representation of this IP address."""
        #   Python 2.x
        return '0x%x' % self._value

    def __index__(self):
        """
        @return: return the integer value of this IP address when called
            by hex(), oct() or bin().
        """
        #   Python 3.x
        return self._value

    def bits(self, word_sep=None):
        """
        @param word_sep: (optional) the separator to insert between words.
            Default: None - use default separator for address type.

        @return: the value of this IP address as a binary digit string."""
        return self._module.int_to_bits(self._value, word_sep)

    @property
    def packed(self):
        """The value of this IP address as a packed binary string."""
        return self._module.int_to_packed(self._value)

    @property
    def words(self):
        """
        A list of unsigned integer words (octets for IPv4, hextets for IPv6)
        found in this IP address.
        """
        return self._module.int_to_words(self._value)

    @property
    def bin(self):
        """
        The value of this IP adddress in standard Python binary
        representational form (0bxxx). A back port of the format provided by
        the builtin bin() function found in Python 2.6.x and higher.
        """
        return self._module.int_to_bin(self._value)

    @property
    def reverse_dns(self):
        """The reverse DNS lookup record for this IP address"""
        return self._module.int_to_arpa(self._value)

    def ipv4(self):
        """
        @return: A numerically equivalent version 4 L{IPAddress} object.
            Raises an L{AddrConversionError} if IPv6 address cannot be
            converted to IPv4.
        """
        ip = None
        klass = self.__class__

        if self.version == 4:
            ip = klass(self._value, 4)
        elif self.version == 6:
            if 0 <= self._value <= _ipv4.max_int:
                ip = klass(self._value, 4)
            elif _ipv4.max_int <= self._value <= 0xffffffffffff:
                ip = klass(self._value - 0xffff00000000, 4)
            else:
                raise AddrConversionError('IPv6 address %s unsuitable for ' \
                    'conversion to IPv4!' % self)
        return ip

    def ipv6(self, ipv4_compatible=False):
        """
        B{Please Note:} the IPv4-mapped IPv6 address format is now considered
        deprecated. See RFC 4291 or later for details.

        @param ipv4_compatible: If C{True} returns an IPv4-mapped address
            (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address
            otherwise. Default: False (IPv4-mapped).

        @return: A numerically equivalent version 6 L{IPAddress} object.
        """
        ip = None
        klass = self.__class__

        if self.version == 6:
            if ipv4_compatible and \
                (0xffff00000000 <= self._value <= 0xffffffffffff):
                ip = klass(self._value - 0xffff00000000, 6)
            else:
                ip = klass(self._value, 6)
        elif self.version == 4:
            #   IPv4-Compatible IPv6 address
            ip = klass(self._value, 6)
            if not ipv4_compatible:
                #   IPv4-Mapped IPv6 address
                ip = klass(0xffff00000000 + self._value, 6)

        return ip

    def format(self, dialect=None):
        """
        Only relevant for IPv6 addresses. Has no effect for IPv4.

        @param dialect: An ipv6_* dialect class.

        @return: an alternate string representation for this IP address.
        """
        if dialect is not None:
            if not hasattr(dialect, 'word_fmt'):
                raise TypeError(
                    'custom dialects should subclass ipv6_verbose!')
        return self._module.int_to_str(self._value, dialect=dialect)

    def __or__(self, other):
        """
        @param other: An L{IPAddress} object (or other int-like object).

        @return: bitwise OR (x | y) between the integer value of this IP
            address and C{other}.
        """
        return self.__class__(self._value | int(other), self.version)

    def __and__(self, other):
        """
        @param other: An L{IPAddress} object (or other int-like object).

        @return: bitwise AND (x & y) between the integer value of this IP
            address and C{other}.
        """
        return self.__class__(self._value & int(other), self.version)

    def __xor__(self, other):
        """
        @param other: An L{IPAddress} object (or other int-like object).

        @return: bitwise exclusive OR (x ^ y) between the integer value of
            this IP address and C{other}.
        """
        return self.__class__(self._value ^ int(other), self.version)

    def __lshift__(self, numbits):
        """
        @param numbits: size of bitwise shift.

        @return: an L{IPAddress} object based on this one with its integer
            value left shifted by C{numbits}.
        """
        return self.__class__(self._value << numbits, self.version)

    def __rshift__(self, numbits):
        """
        @param numbits: size of bitwise shift.

        @return: an L{IPAddress} object based on this one with its integer
            value right shifted by C{numbits}.
        """
        return self.__class__(self._value >> numbits, self.version)

    def __nonzero__(self):
        """
        @return: C{True} if the numerical value of this IP address is not zero,
            C{False} otherwise.
        """
        #   Python 2.x.
        return bool(self._value)

    __bool__ = __nonzero__  #   Python 3.x.

    def __str__(self):
        """@return: IP address in presentational format"""
        return self._module.int_to_str(self._value)

    def __repr__(self):
        """@return: Python statement to create an equivalent object"""
        return "%s('%s')" % (self.__class__.__name__, self)

#-----------------------------------------------------------------------------
class IPListMixin(object):
    """
    A mixin class providing shared list-like functionality to classes
    representing groups of IP addresses.

    """
    def __iter__(self):
        """
        @return: An iterator providing access to all L{IPAddress} objects
            within range represented by this ranged IP object.
        """
        start_ip = IPAddress(self.first, self.version)
        end_ip = IPAddress(self.last, self.version)
        return iter_iprange(start_ip, end_ip)

    @property
    def size(self):
        """
        The total number of IP addresses within this ranged IP object.
        """
        return int(self.last - self.first + 1)

    def __len__(self):
        """
        @return: the number of IP addresses in this ranged IP object. Raises
            an C{IndexError} if size > system max int (a Python 2.x
            limitation). Use the .size property for subnets of any size.
        """
        size = self.size
        if size > _sys_maxint:
            raise IndexError(("range contains more than %d (index size max) "
               "IP addresses! Use the .size property instead." % _sys_maxint))
        return size

    def __getitem__(self, index):
        """
        @return: The IP address(es) in this L{IPNetwork} object referenced by
            index or slice. As slicing can produce large sequences of objects
            an iterator is returned instead of the more usual C{list}.
        """
        item = None

        if hasattr(index, 'indices'):
            if self._module.version == 6:
                raise TypeError('IPv6 slices are not supported!')

            (start, stop, step) = index.indices(self.size)

            if (start + step < 0) or (step > stop):
                #   step value exceeds start and stop boundaries.
                item = iter([IPAddress(self.first, self.version)])
            else:
                start_ip = IPAddress(self.first + start, self.version)
                end_ip = IPAddress(self.first + stop - step, self.version)
                item = iter_iprange(start_ip, end_ip, step)
        else:
            try:
                index = int(index)
                if (- self.size) <= index < 0:
                    #   negative index.
                    item = IPAddress(self.last + index + 1, self.version)
                elif 0 <= index <= (self.size - 1):
                    #   Positive index or zero index.
                    item = IPAddress(self.first + index, self.version)
                else:
                    raise IndexError('index out range for address range size!')
            except ValueError:
                raise TypeError('unsupported index type %r!' % index)

        return item

    def __contains__(self, other):
        """
        @param other: an L{IPAddress} or ranged IP object.

        @return: C{True} if other falls within the boundary of this one,
            C{False} otherwise.
        """
        if self.version != other.version:
            return False
        if hasattr(other, '_value') and not hasattr(other, '_prefixlen'):
            return other._value >= self.first and other._value <= self.last
        return other.first >= self.first and other.last <= self.last

    def __nonzero__(self):
        """
        Ranged IP objects always represent a sequence of at least one IP
        address and are therefore always True in the boolean context.
        """
        #   Python 2.x.
        return True

    __bool__ = __nonzero__  #   Python 3.x.

#-----------------------------------------------------------------------------
def parse_ip_network(module, addr, implicit_prefix=False, flags=0):
    if isinstance(addr, tuple):
        #   CIDR integer tuple
        try:
            val1, val2 = addr
        except ValueError:
            raise AddrFormatError('invalid %s tuple!' % module.family_name)

        if 0 <= val1 <= module.max_int:
            value = val1
            if 0 <= val2 <= module.width:
                prefixlen = val2
            else:
                raise AddrFormatError('invalid prefix for %s tuple!' \
                    % module.family_name)
        else:
            raise AddrFormatError('invalid address value for %s tuple!' \
                % module.family_name)
    elif isinstance(addr, _str_type):
        #   CIDR-like string subnet
        if implicit_prefix:
            #TODO: deprecate this option in netaddr 0.8.x
            addr = cidr_abbrev_to_verbose(addr)
        try:
            if '/' in addr:
                val1, val2 = addr.split('/', 1)
            else:
                val1 = addr
                val2 = None
        except ValueError:
            raise AddrFormatError('invalid IPNetwork address %s!' % addr)

        try:
            ip = IPAddress(val1, module.version, flags=INET_PTON)
        except AddrFormatError:
            if module.version == 4:
                #   Try a partial IPv4 network address...
                expanded_addr = _ipv4.expand_partial_address(val1)
                ip = IPAddress(expanded_addr, module.version, flags=INET_PTON)
            else:
                raise AddrFormatError('invalid IPNetwork address %s!' % addr)
        value = ip._value

        try:
            #   Integer CIDR prefix.
            prefixlen = int(val2)
        except TypeError:
            if val2 is None:
                #   No prefix was specified.
                prefixlen = module.width
        except ValueError:
            #   Not an integer prefix, try a netmask/hostmask prefix.
            mask = IPAddress(val2, module.version, flags=INET_PTON)
            if mask.is_netmask():
                prefixlen = module.netmask_to_prefix[mask._value]
            elif mask.is_hostmask():
                prefixlen = module.hostmask_to_prefix[mask._value]
            else:
                raise AddrFormatError('addr %r is not a valid IPNetwork!' \
                    % addr)

        if not 0 <= prefixlen <= module.width:
            raise AddrFormatError('invalid prefix for %s address!' \
                % module.family_name)
    else:
        raise TypeError('unexpected type %s for addr arg' % type(addr))

    if flags & NOHOST:
        #   Remove host bits.
        netmask = module.prefix_to_netmask[prefixlen]
        value = value & netmask

    return value, prefixlen

#-----------------------------------------------------------------------------
class IPNetwork(BaseIP, IPListMixin):
    """
    An IPv4 or IPv6 network or subnet. A combination of an IP address and a
    network mask.

    Accepts CIDR and several variants :-

    a) Standard CIDR::

        x.x.x.x/y -> 192.0.2.0/24
        x::/y -> fe80::/10

    b) Hybrid CIDR format (netmask address instead of prefix)::

        x.x.x.x/y.y.y.y -> 192.0.2.0/255.255.255.0
        x::/y:: -> fe80::/ffc0::

    where 'y' address represent a valid netmask.

    c) ACL hybrid CIDR format (hostmask address instead of prefix)::

        x.x.x.x/y.y.y.y -> 192.0.2.0/0.0.0.255
        x::/y:: -> fe80::/3f:ffff:ffff:ffff:ffff:ffff:ffff:ffff

    where 'y' address represent a valid netmask.

    This is like Cisco's ACL bitmasks.

    d) Abbreviated CIDR format (as of netaddr 0.7.x this requires
    the optional constructor argument C{implicit_prefix=True})::

        x       -> 192
        x/y     -> 10/8
        x.x/y   -> 192.168/16
        x.x.x/y -> 192.168.0/24

    which are equivalent to::

        x.0.0.0/y   -> 192.0.0.0/24
        x.0.0.0/y   -> 10.0.0.0/8
        x.x.0.0/y   -> 192.168.0.0/16
        x.x.x.0/y   -> 192.168.0.0/24

    """
    __slots__ = ('_prefixlen',)

    def __init__(self, addr, implicit_prefix=False, version=None, flags=0):
        """
        Constructor.

        @param addr: an IPv4 or IPv6 address with optional CIDR prefix,
            netmask or hostmask. May be an IP address in presentation
            (string) format, an tuple containing and integer address and a
            network prefix, or another IPAddress/IPNetwork object (copy
            construction).

        @param implicit_prefix: (optional) if True, the constructor uses
            classful IPv4 rules to select a default prefix when one is not
            provided. If False it uses the length of the IP address version.
            (default: False)

        @param version: (optional) optimizes version detection if specified
            and distinguishes between IPv4 and IPv6 for addresses with an
            equivalent integer value.

        @param flags: (optional) decides which rules are applied to the
            interpretation of the addr value. Currently only supports the
            NOHOST option. See the netaddr.core docs for further details.

        """
        super(IPNetwork, self).__init__()

        value, prefixlen, module = None, None, None

        if hasattr(addr, '_prefixlen'):
            #   IPNetwork object copy constructor
            value = addr._value
            module = addr._module
            prefixlen = addr._prefixlen
        elif hasattr(addr, '_value'):
            #   IPAddress object copy constructor
            value = addr._value
            module = addr._module
            prefixlen = module.width
        elif version == 4:
            value, prefixlen = parse_ip_network(_ipv4, addr,
                implicit_prefix=implicit_prefix, flags=flags)
            module = _ipv4
        elif version == 6:
            value, prefixlen = parse_ip_network(_ipv6, addr,
                implicit_prefix=implicit_prefix, flags=flags)
            module = _ipv6
        else:
            if version is not None:
                raise ValueError('%r is an invalid IP version!' % version)
            try:
                module = _ipv4
                value, prefixlen = parse_ip_network(module, addr,
                    implicit_prefix, flags)
            except AddrFormatError:
                try:
                    module = _ipv6
                    value, prefixlen = parse_ip_network(module, addr,
                        implicit_prefix, flags)
                except AddrFormatError:
                    pass

                if value is None:
                    raise AddrFormatError('invalid IPNetwork %s' % addr)

        self._value = value
        self._prefixlen = prefixlen
        self._module = module

    def __getstate__(self):
        """@return: Pickled state of an C{IPNetwork} object."""
        return self._value, self._prefixlen, self._module.version

    def __setstate__(self, state):
        """
        @param state: data used to unpickle a pickled C{IPNetwork} object.

        """
        value, prefixlen, version = state

        self._value = value

        if version == 4:
            self._module = _ipv4
        elif version == 6:
            self._module = _ipv6
        else:
            raise ValueError('unpickling failed for object state %s' \
                % str(state))

        if 0 <= prefixlen <= self._module.width:
            self._prefixlen = prefixlen
        else:
            raise ValueError('unpickling failed for object state %s' \
                % str(state))

    def _set_prefixlen(self, value):
        if not isinstance(value, _int_type):
            raise TypeError('int argument expected, not %s' % type(value))
        if not 0 <= value <= self._module.width:
            raise AddrFormatError('invalid prefix for an %s address!' \
                % self._module.family_name)
        self._prefixlen = value

    prefixlen = property(lambda self: self._prefixlen, _set_prefixlen,
        doc='size of the bitmask used to separate the network from the host bits')

    @property
    def ip(self):
        """
        The IP address of this L{IPNetwork} object. This is may or may not be
        the same as the network IP address which varies according to the value
        of the CIDR subnet prefix.
        """
        return IPAddress(self._value, self.version)

    @property
    def network(self):
        """The network address of this L{IPNetwork} object."""
        return IPAddress(self._value & int(self.netmask), self.version)

    @property
    def broadcast(self):
        """The broadcast address of this L{IPNetwork} object"""
        return IPAddress(self._value | self.hostmask._value, self.version)

    @property
    def first(self):
        """
        The integer value of first IP address found within this L{IPNetwork}
        object.
        """
        return self._value & (self._module.max_int ^ self.hostmask._value)

    @property
    def last(self):
        """
        The integer value of last IP address found within this L{IPNetwork}
        object.
        """
        hostmask = (1 << (self._module.width - self._prefixlen)) - 1
        return self._value | hostmask

    @property
    def netmask(self):
        """The subnet mask of this L{IPNetwork} object."""
        netmask = self._module.max_int ^ self.hostmask._value
        return IPAddress(netmask, self.version)

    @property
    def hostmask(self):
        """The host mask of this L{IPNetwork} object."""
        hostmask = (1 << (self._module.width - self._prefixlen)) - 1
        return IPAddress(hostmask, self.version)

    @property
    def cidr(self):
        """
        The true CIDR address for this L{IPNetwork} object which omits any
        host bits to the right of the CIDR subnet prefix.
        """
        ip = IPAddress(self._value & int(self.netmask), self.version)
        cidr = IPNetwork("%s/%d" % (ip, self.prefixlen))
        return cidr

    def __iadd__(self, num):
        """
        Increases the value of this L{IPNetwork} object by the current size
        multiplied by C{num}.

        @param num: (optional) number of L{IPNetwork} blocks to increment this
        IPNetwork's value by.

        An C{IndexError} is raised if result exceeds maximum IP address value
        or is less than zero.
        """
        new_value = int(self.network) + (self.size * num)

        if (new_value + (self.size - 1)) > self._module.max_int:
            raise IndexError('increment exceeds address boundary!')
        if new_value < 0:
            raise IndexError('increment is less than zero!')

        self._value = new_value
        return self

    def __isub__(self, num):
        """
        Decreases the value of this L{IPNetwork} object by the current size
        multiplied by C{num}.

        @param num: (optional) number of L{IPNetwork} blocks to decrement this
        IPNetwork's value by.

        An C{IndexError} is raised if result is less than zero or exceeds
        maximum IP address value.
        """
        new_value = int(self.network) - (self.size * num)

        if new_value < 0:
            raise IndexError('decrement is less than zero!')
        if (new_value + (self.size - 1)) > self._module.max_int:
            raise IndexError('decrement exceeds address boundary!')

        self._value = new_value
        return self

    def key(self):
        """
        @return: A key tuple used to uniquely identify this L{IPNetwork}.
        """
        return self.version, self.first, self.last

    def sort_key(self):
        """
        @return: A key tuple used to compare and sort this L{IPNetwork}
            correctly.
        """
        net_size_bits = self._module.width - num_bits(self.size)
        host_bits = self._value - self.first
        return self.version, self.first, net_size_bits, host_bits

    def ipv4(self):
        """
        @return: A numerically equivalent version 4 L{IPNetwork} object.
            Raises an L{AddrConversionError} if IPv6 address cannot be
            converted to IPv4.
        """
        ip = None
        klass = self.__class__

        if self.version == 4:
            ip = klass('%s/%d' % (self.ip, self.prefixlen))
        elif self.version == 6:
            if 0 <= self._value <= _ipv4.max_int:
                addr = _ipv4.int_to_str(self._value)
                ip = klass('%s/%d' % (addr, self.prefixlen - 96))
            elif _ipv4.max_int <= self._value <= 0xffffffffffff:
                addr = _ipv4.int_to_str(self._value - 0xffff00000000)
                ip = klass('%s/%d' % (addr, self.prefixlen - 96))
            else:
                raise AddrConversionError('IPv6 address %s unsuitable for ' \
                    'conversion to IPv4!' % self)
        return ip

    def ipv6(self, ipv4_compatible=False):
        """
        B{Please Note:} the IPv4-mapped IPv6 address format is now considered
        deprecated. See RFC 4291 or later for details.

        @param ipv4_compatible: If C{True} returns an IPv4-mapped address
            (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address
            otherwise. Default: False (IPv4-mapped).

        @return: A numerically equivalent version 6 L{IPNetwork} object.
        """
        ip = None
        klass = self.__class__

        if self.version == 6:
            if ipv4_compatible and \
                (0xffff00000000 <= self._value <= 0xffffffffffff):
                ip = klass((self._value - 0xffff00000000, self._prefixlen),
                    version=6)
            else:
                ip = klass((self._value, self._prefixlen), version=6)
        elif self.version == 4:
            if ipv4_compatible:
                #   IPv4-Compatible IPv6 address
                ip = klass((self._value, self._prefixlen + 96), version=6)
            else:
                #   IPv4-Mapped IPv6 address
                ip = klass((0xffff00000000 + self._value,
                            self._prefixlen + 96), version=6)

        return ip

    def previous(self, step=1):
        """
        @param step: the number of IP subnets between this L{IPNetwork} object
            and the expected subnet. Default: 1 (the previous IP subnet).

        @return: The adjacent subnet preceding this L{IPNetwork} object.
        """
        ip_copy = self.__class__('%s/%d' % (self.network, self.prefixlen),
            self.version)
        ip_copy -= step
        return ip_copy

    def next(self, step=1):
        """
        @param step: the number of IP subnets between this L{IPNetwork} object
            and the expected subnet. Default: 1 (the next IP subnet).

        @return: The adjacent subnet succeeding this L{IPNetwork} object.
        """
        ip_copy = self.__class__('%s/%d' % (self.network, self.prefixlen),
            self.version)
        ip_copy += step
        return ip_copy

    def supernet(self, prefixlen=0):
        """
        Provides a list of supernets for this L{IPNetwork} object between the
        size of the current prefix and (if specified) an endpoint prefix.

        @param prefixlen: (optional) a CIDR prefix for the maximum supernet.
            Default: 0 - returns all possible supernets.

        @return: a tuple of supernet L{IPNetwork} objects.
        """
        if not 0 <= prefixlen <= self._module.width:
            raise ValueError('CIDR prefix /%d invalid for IPv%d!' \
                % (prefixlen, self.version))

        #   Use a copy of self as we'll be editing it.
        supernet = self.cidr

        supernets = []
        while supernet.prefixlen > prefixlen:
            supernet.prefixlen -= 1
            supernets.append(supernet.cidr)

        return list(reversed(supernets))

    def subnet(self, prefixlen, count=None, fmt=None):
        """
        A generator that divides up this IPNetwork's subnet into smaller
        subnets based on a specified CIDR prefix.

        @param prefixlen: a CIDR prefix indicating size of subnets to be
            returned.

        @param count: (optional) number of consecutive IP subnets to be
            returned.

        @return: an iterator containing IPNetwork subnet objects.
        """
        if not 0 <= self.prefixlen <= self._module.width:
            raise ValueError('CIDR prefix /%d invalid for IPv%d!' \
                % (prefixlen, self.version))

        if not self.prefixlen <= prefixlen:
            #   Don't return anything.
            raise StopIteration

        #   Calculate number of subnets to be returned.
        width = self._module.width
        max_subnets = 2 ** (width - self.prefixlen) // 2 ** (width - prefixlen)

        if count is None:
            count = max_subnets

        if not 1 <= count <= max_subnets:
            raise ValueError('count outside of current IP subnet boundary!')

        base_subnet = self._module.int_to_str(self.first)

        for i in _iter_range(count):
            subnet = self.__class__('%s/%d' % (base_subnet, prefixlen),
                self.version)
            subnet.value += (subnet.size * i)
            subnet.prefixlen = prefixlen
            yield subnet

    def iter_hosts(self):
        """
        @return: An iterator that provides all IP addresses that can be
            assigned to hosts within the range of this IP object's subnet.
                - for IPv4, the network and broadcast addresses are always
                excluded. Any subnet that contains less than 4 IP addresses
                yields an empty list.
                - for IPv6, only the unspecified address '::' is excluded
                from any yielded IP addresses.
        """
        it_hosts = iter([])

        if self.version == 4:
            #   IPv4 logic.
            if self.size >= 4:
                it_hosts = iter_iprange(IPAddress(self.first+1, self.version),
                                        IPAddress(self.last-1, self.version))
        else:
            #   IPv6 logic.
            if self.first == 0:
                if self.size != 1:
                    #   Don't return '::'.
                    it_hosts = iter_iprange(
                        IPAddress(self.first+1, self.version),
                        IPAddress(self.last, self.version))
            else:
                it_hosts = iter(self)

        return it_hosts

    def __str__(self):
        """@return: this IPNetwork in CIDR format"""
        addr = self._module.int_to_str(self._value)
        return "%s/%s" % (addr, self.prefixlen)

    def __repr__(self):
        """@return: Python statement to create an equivalent object"""
        return "%s('%s')" % (self.__class__.__name__, self)

#-----------------------------------------------------------------------------
class IPRange(BaseIP, IPListMixin):
    """
    An arbitrary IPv4 or IPv6 address range.

    Formed from a lower and upper bound IP address. The upper bound IP cannot
    be numerically smaller than the lower bound and the IP version of both
    must match.

    """
    __slots__ = ('_start', '_end')

    def __init__(self, start, end, flags=0):
        """
        Constructor.

        @param start: an IPv4 or IPv6 address that forms the lower
            boundary of this IP range.

        @param end: an IPv4 or IPv6 address that forms the upper
            boundary of this IP range.

        @param flags: (optional) decides which rules are applied to the
            interpretation of the start and end values. Supported constants
            are INET_PTON and ZEROFILL. See the netaddr.core docs for further
            details.

        """
        self._start = IPAddress(start, flags=flags)
        self._module = self._start._module
        self._end = IPAddress(end, self._module.version, flags=flags)
        if int(self._start) > int(self._end):
            raise AddrFormatError('lower bound IP greater than upper bound!')

    def __getstate__(self):
        """@return: Pickled state of an C{IPRange} object."""
        return self._start.value, self._end.value, self._module.version

    def __setstate__(self, state):
        """
        @param state: data used to unpickle a pickled C{IPRange} object.

        """
        start, end, version = state

        self._start = IPAddress(start, version)
        self._module = self._start._module
        self._end = IPAddress(end, version)

    @property
    def first(self):
        """The integer value of first IP address in this L{IPRange} object."""
        return int(self._start)

    @property
    def last(self):
        """The integer value of last IP address in this L{IPRange} object."""
        return int(self._end)

    def key(self):
        """
        @return: A key tuple used to uniquely identify this L{IPRange}.
        """
        return self.version, self.first, self.last

    def sort_key(self):
        """
        @return: A key tuple used to compare and sort this L{IPRange}
            correctly.
        """
        skey = self._module.width - num_bits(self.size)
        return self.version, self.first, skey

    def cidrs(self):
        """
        The list of CIDR addresses found within the lower and upper bound
        addresses of this L{IPRange}.
        """
        return iprange_to_cidrs(self._start, self._end)

    def __str__(self):
        """@return: this L{IPRange} in a common representational format."""
        return "%s-%s" % (self._start, self._end)

    def __repr__(self):
        """@return: Python statement to create an equivalent object"""
        return "%s('%s', '%s')" % (self.__class__.__name__,
            self._start, self._end)

#-----------------------------------------------------------------------------
def iter_unique_ips(*args):
    """
    @param args: A list of IP addresses and subnets passed in as arguments.

    @return: A generator that flattens out IP subnets, yielding unique
        individual IP addresses (no duplicates).
    """
    for cidr in cidr_merge(args):
        for ip in cidr:
            yield ip

#-----------------------------------------------------------------------------
def cidr_abbrev_to_verbose(abbrev_cidr):
    """
    A function that converts abbreviated IPv4 CIDRs to their more verbose
    equivalent.

    @param abbrev_cidr: an abbreviated CIDR.

    Uses the old-style classful IP address rules to decide on a default
    subnet prefix if one is not explicitly provided.

    Only supports IPv4 addresses.

    Examples ::

        10                  - 10.0.0.0/8
        10/16               - 10.0.0.0/16
        128                 - 128.0.0.0/16
        128/8               - 128.0.0.0/8
        192.168             - 192.168.0.0/16

    @return: A verbose CIDR from an abbreviated CIDR or old-style classful
    network address, The original value if it was not recognised as a
    supported abbreviation.
    """
    #   Internal function that returns a prefix value based on the old IPv4
    #   classful network scheme that has been superseded (almost) by CIDR.
    def classful_prefix(octet):
        octet = int(octet)
        if not 0 <= octet <= 255:
            raise IndexError('Invalid octet: %r!' % octet)
        if 0 <= octet <= 127:       #   Legacy class 'A' classification.
            return 8
        elif 128 <= octet <= 191:   #   Legacy class 'B' classification.
            return 16
        elif 192 <= octet <= 223:   #   Legacy class 'C' classification.
            return 24
        elif 224 <= octet <= 239:   #   Multicast address range.
            return 4
        return 32                   #   Default.

    start = ''
    tokens = []
    prefix = None

    if _is_str(abbrev_cidr):
        if ':' in abbrev_cidr:
            return abbrev_cidr
    try:
        #   Single octet partial integer or string address.
        i = int(abbrev_cidr)
        tokens = [str(i), '0', '0', '0']
        return "%s%s/%s" % (start, '.'.join(tokens), classful_prefix(i))

    except ValueError:
        #   Multi octet partial string address with optional prefix.
        part_addr = abbrev_cidr
        tokens = []

        if part_addr == '':
            #   Not a recognisable format.
            return abbrev_cidr

        if '/' in part_addr:
            (part_addr, prefix) = part_addr.split('/', 1)

        #   Check prefix for validity.
        if prefix is not None:
            try:
                if not 0 <= int(prefix) <= 32:
                    raise ValueError('prefixlen in address %r out of range' \
                        ' for IPv4!' % abbrev_cidr)
            except ValueError:
                return abbrev_cidr

        if '.' in part_addr:
            tokens = part_addr.split('.')
        else:
            tokens = [part_addr]

        if 1 <= len(tokens) <= 4:
            for i in range(4 - len(tokens)):
                tokens.append('0')
        else:
            #   Not a recognisable format.
            return abbrev_cidr

        if prefix is None:
            try:
                prefix = classful_prefix(tokens[0])
            except ValueError:
                return abbrev_cidr

        return "%s%s/%s" % (start, '.'.join(tokens), prefix)

    except TypeError:
        pass
    except IndexError:
        pass

    #   Not a recognisable format.
    return abbrev_cidr

#-----------------------------------------------------------------------------
def cidr_merge(ip_addrs):
    """
    A function that accepts an iterable sequence of IP addresses and subnets
    merging them into the smallest possible list of CIDRs. It merges adjacent
    subnets where possible, those contained within others and also removes
    any duplicates.

    @param ip_addrs: an iterable sequence of IP addresses and subnets.

    @return: a summarized list of L{IPNetwork} objects.
    """
    if not hasattr(ip_addrs, '__iter__') or hasattr(ip_addrs, 'keys'):
        raise ValueError('A sequence or iterator is expected!')

    #   Start off using set as we'll remove any duplicates at the start.
    ipv4_bit_cidrs = set()
    ipv6_bit_cidrs = set()

    #   Convert IP addresses and subnets into their CIDR bit strings.
    ipv4_match_all_found = False
    ipv6_match_all_found = False

    for ip in ip_addrs:
        cidr = IPNetwork(ip)
        bits = cidr.network.bits(word_sep='')[0:cidr.prefixlen]

        if cidr.version == 4:
            if bits == '':
                ipv4_match_all_found = True
                ipv4_bit_cidrs = set([''])  # Clear all other IPv4 values.

            if not ipv4_match_all_found:
                ipv4_bit_cidrs.add(bits)
        else:
            if bits == '':
                ipv6_match_all_found = True
                ipv6_bit_cidrs = set([''])  # Clear all other IPv6 values.

            if not ipv6_match_all_found:
                ipv6_bit_cidrs.add(bits)

    #   Merge binary CIDR addresses where possible.
    def _reduce_bit_cidrs(cidrs):
        new_cidrs = []

        cidrs.sort()

        #   Multiple passes are required to obtain precise results.
        while 1:
            finished = True
            while len(cidrs) > 0:
                if len(new_cidrs) == 0:
                    new_cidrs.append(cidrs.pop(0))
                if len(cidrs) == 0:
                    break
                #   lhs and rhs are same size and adjacent.
                (new_cidr, subs) = RE_CIDR_ADJACENT.subn(
                    r'\1', '%s %s' % (new_cidrs[-1], cidrs[0]))
                if subs:
                    #   merge lhs with rhs.
                    new_cidrs[-1] = new_cidr
                    cidrs.pop(0)
                    finished = False
                else:
                    #   lhs contains rhs.
                    (new_cidr, subs) = RE_CIDR_WITHIN.subn(
                        r'\1', '%s %s' % (new_cidrs[-1], cidrs[0]))
                    if subs:
                        #   keep lhs, discard rhs.
                        new_cidrs[-1] = new_cidr
                        cidrs.pop(0)
                        finished = False
                    else:
                        #   no matches - accept rhs.
                        new_cidrs.append(cidrs.pop(0))
            if finished:
                break
            else:
                #   still seeing matches, reset.
                cidrs = new_cidrs
                new_cidrs = []

        if new_cidrs == ['0', '1']:
            #   Special case where summary CIDR result is '0.0.0.0/0' or
            #   '::/0' i.e. the whole IPv4 or IPv6 address space.
            new_cidrs = ['']

        return new_cidrs

    new_cidrs = []

    def _bits_to_cidr(bits, module):
        if bits == '':
            if module.version == 4:
                return IPNetwork('0.0.0.0/0', 4)
            else:
                return IPNetwork('::/0', 6)

        if RE_VALID_CIDR_BITS.match(bits) is None:
            raise ValueError('%r is an invalid bit string!' % bits)

        num_bits = len(bits)

        if bits == '':
            return IPAddress(module.int_to_str(0), module.version)
        else:
            bits = bits + '0' * (module.width - num_bits)
            return IPNetwork((module.bits_to_int(bits), num_bits),
                version=module.version)

    #   Reduce and format lists of reduced CIDRs.
    for bits in _reduce_bit_cidrs(list(ipv4_bit_cidrs)):
        new_cidrs.append(_bits_to_cidr(bits, _ipv4))

    for bits in _reduce_bit_cidrs(list(ipv6_bit_cidrs)):
        new_cidrs.append(_bits_to_cidr(bits, _ipv6))

    return new_cidrs

#-----------------------------------------------------------------------------
def cidr_exclude(target, exclude):
    """
    Removes an exclude IP address or subnet from target IP subnet.

    @param target: the target IP address or subnet to be divided up.

    @param exclude: the IP address or subnet to be removed from target.

    @return: list of L{IPNetwork} objects remaining after exclusion.
    """
    cidrs = []

    target = IPNetwork(target)
    exclude = IPNetwork(exclude)

    if exclude.last < target.first:
        #   Exclude subnet's upper bound address less than target
        #   subnet's lower bound.
        return [target.cidr]
    elif target.last < exclude.first:
        #   Exclude subnet's lower bound address greater than target
        #   subnet's upper bound.
        return [target.cidr]

    new_prefixlen = target.prefixlen + 1

    if new_prefixlen <= target._module.width:
        i_lower = target.first
        i_upper = target.first + (2 ** (target._module.width - new_prefixlen))

        lower = IPNetwork((i_lower, new_prefixlen))
        upper = IPNetwork((i_upper, new_prefixlen))

        while exclude.prefixlen >= new_prefixlen:
            if exclude in lower:
                matched = i_lower
                unmatched = i_upper
            elif exclude in upper:
                matched = i_upper
                unmatched = i_lower
            else:
                #   Exclude subnet not within target subnet.
                cidrs.append(target.cidr)
                break

            ip = IPNetwork((unmatched, new_prefixlen))

            cidrs.append(ip)

            new_prefixlen += 1

            if new_prefixlen > target._module.width:
                break

            i_lower = matched
            i_upper = matched + (2 ** (target._module.width - new_prefixlen))

            lower = IPNetwork((i_lower, new_prefixlen))
            upper = IPNetwork((i_upper, new_prefixlen))

    cidrs.sort()

    return cidrs

#-----------------------------------------------------------------------------
def spanning_cidr(ip_addrs):
    """
    Function that accepts a sequence of IP addresses and subnets returning
    a single L{IPNetwork} subnet that is large enough to span the lower and
    upper bound IP addresses with a possible overlap on either end.

    @param ip_addrs: sequence of IP addresses and subnets.

    @return: a single spanning L{IPNetwork} subnet.
    """
    sorted_ips = sorted(
        [IPNetwork(ip) for ip in ip_addrs])

    if not len(sorted_ips) > 1:
        raise ValueError('IP sequence must contain at least 2 elements!')

    lowest_ip = sorted_ips[0]
    highest_ip = sorted_ips[-1]

    if lowest_ip.version != highest_ip.version:
        raise TypeError('IP sequence cannot contain both IPv4 and IPv6!')

    ip = highest_ip.cidr

    while ip.prefixlen > 0:
        if highest_ip in ip and lowest_ip not in ip:
            ip.prefixlen -= 1
        else:
            break

    return ip.cidr

#-----------------------------------------------------------------------------
def iter_iprange(start, end, step=1):
    """
    A generator that produces IPAddress objects between an arbitrary start
    and stop IP address with intervals of step between them. Sequences
    produce are inclusive of boundary IPs.

    @param start: start IP address.

    @param end: end IP address.

    @param step: (optional) size of step between IP addresses. Default: 1

    @return: an iterator of one or more L{IPAddress} objects.
    """
    start = IPAddress(start)
    end = IPAddress(end)

    if start.version != end.version:
        raise TypeError('start and stop IP versions do not match!')
    version = start.version

    step = int(step)
    if step == 0:
        raise ValueError('step argument cannot be zero')

    #   We don't need objects from here, just integers.
    start = int(start)
    stop = int(end)

    negative_step = False

    if step < 0:
        negative_step = True

    index = start - step
    while True:
        index += step
        if negative_step:
            if not index >= stop:
                break
        else:
            if not index <= stop:
                break
        yield IPAddress(index, version)


#-----------------------------------------------------------------------------
def iprange_to_cidrs(start, end):
    """
    A function that accepts an arbitrary start and end IP address or subnet
    and returns a list of CIDR subnets that fit exactly between the boundaries
    of the two with no overlap.

    @param start: the start IP address or subnet.

    @param end: the end IP address or subnet.

    @return: a list of one or more IP addresses and subnets.
    """
    cidr_list = []

    start = IPNetwork(start)
    end = IPNetwork(end)

    iprange = [start.first, end.last]

    #   Get spanning CIDR covering both addresses.
    cidr_span = spanning_cidr([start, end])

    if cidr_span.first == iprange[0] and cidr_span.last == iprange[-1]:
        #   Spanning CIDR matches start and end exactly.
        cidr_list = [cidr_span]
    elif cidr_span.last == iprange[-1]:
        #   Spanning CIDR matches end exactly.
        ip = IPAddress(start)
        first_int_val = int(ip)
        ip -= 1
        cidr_remainder = cidr_exclude(cidr_span, ip)

        first_found = False
        for cidr in cidr_remainder:
            if cidr.first == first_int_val:
                first_found = True
            if first_found:
                cidr_list.append(cidr)
    elif cidr_span.first == iprange[0]:
        #   Spanning CIDR matches start exactly.
        ip = IPAddress(end)
        last_int_val = int(ip)
        ip += 1
        cidr_remainder = cidr_exclude(cidr_span, ip)

        last_found = False
        for cidr in cidr_remainder:
            cidr_list.append(cidr)
            if cidr.last == last_int_val:
                break
    elif cidr_span.first <= iprange[0] and cidr_span.last >= iprange[-1]:
        #   Spanning CIDR overlaps start and end.
        ip = IPAddress(start)
        first_int_val = int(ip)
        ip -= 1
        cidr_remainder = cidr_exclude(cidr_span, ip)

        #   Fix start.
        first_found = False
        for cidr in cidr_remainder:
            if cidr.first == first_int_val:
                first_found = True
            if first_found:
                cidr_list.append(cidr)

        #   Fix end.
        ip = IPAddress(end)
        last_int_val = int(ip)
        ip += 1
        cidr_remainder = cidr_exclude(cidr_list.pop(), ip)

        last_found = False
        for cidr in cidr_remainder:
            cidr_list.append(cidr)
            if cidr.last == last_int_val:
                break

    return cidr_list

#-----------------------------------------------------------------------------
def smallest_matching_cidr(ip, cidrs):
    """
    Matches an IP address or subnet against a given sequence of IP addresses
    and subnets.

    @param ip: a single IP address or subnet.

    @param cidrs: a sequence of IP addresses and/or subnets.

    @return: the smallest (most specific) matching IPAddress or IPNetwork
        object from the provided sequence, None if there was no match.
    """
    match = None

    if not hasattr(cidrs, '__iter__'):
        raise TypeError('IP address/subnet sequence expected, not %r!'
            % cidrs)

    ip = IPAddress(ip)
    for cidr in sorted([IPNetwork(cidr) for cidr in cidrs]):
        if ip in cidr:
            match = cidr
        else:
            if match is not None:
                break

    return match

#-----------------------------------------------------------------------------
def largest_matching_cidr(ip, cidrs):
    """
    Matches an IP address or subnet against a given sequence of IP addresses
    and subnets.

    @param ip: a single IP address or subnet.

    @param cidrs: a sequence of IP addresses and/or subnets.

    @return: the largest (least specific) matching IPAddress or IPNetwork
        object from the provided sequence, None if there was no match.
    """
    match = None

    if not hasattr(cidrs, '__iter__'):
        raise TypeError('IP address/subnet sequence expected, not %r!'
            % cidrs)

    ip = IPAddress(ip)
    for cidr in sorted([IPNetwork(cidr) for cidr in cidrs]):
        if ip in cidr:
            match = cidr
            break

    return match

#-----------------------------------------------------------------------------
def all_matching_cidrs(ip, cidrs):
    """
    Matches an IP address or subnet against a given sequence of IP addresses
    and subnets.

    @param ip: a single IP address or subnet.

    @param cidrs: a sequence of IP addresses and/or subnets.

    @return: all matching IPAddress and/or IPNetwork objects from the provided
        sequence, an empty list if there was no match.
    """
    matches = []

    if not hasattr(cidrs, '__iter__'):
        raise TypeError('IP address/subnet sequence expected, not %r!'
            % cidrs)

    ip = IPAddress(ip)
    for cidr in sorted([IPNetwork(cidr) for cidr in cidrs]):
        if ip in cidr:
            matches.append(cidr)
        else:
            if matches:
                break

    return matches

#-----------------------------------------------------------------------------
#   Cached IPv4 address range lookups.
#-----------------------------------------------------------------------------
IPV4_LOOPBACK  = IPNetwork('127.0.0.0/8')

IPV4_PRIVATE = (
    IPNetwork('10.0.0.0/8'),                    #   Private-Use Networks
    IPNetwork('172.16.0.0/12'),                 #   Private-Use Networks
    IPNetwork('192.0.2.0/24'),                  #   Test-Net
    IPNetwork('192.168.0.0/16'),                #   Private-Use Networks
    IPRange('239.0.0.0', '239.255.255.255'),    #   Administrative Multicast
)

IPV4_LINK_LOCAL = IPNetwork('169.254.0.0/16')

IPV4_MULTICAST = IPNetwork('224.0.0.0/4')

IPV4_6TO4 = IPNetwork('192.88.99.0/24')    #   6to4 Relay Anycast

IPV4_RESERVED = (
    IPNetwork('39.0.0.0/8'),        #   Reserved but subject to allocation
    IPNetwork('128.0.0.0/16'),      #   Reserved but subject to allocation
    IPNetwork('191.255.0.0/16'),    #   Reserved but subject to allocation
    IPNetwork('192.0.0.0/24'),      #   Reserved but subject to allocation
    IPNetwork('223.255.255.0/24'),  #   Reserved but subject to allocation
    IPNetwork('240.0.0.0/4'),       #   Reserved for Future Use

    #   Reserved multicast
    IPRange('234.0.0.0', '238.255.255.255'),
    IPRange('225.0.0.0', '231.255.255.255'),
)

#-----------------------------------------------------------------------------
#   Cached IPv6 address range lookups.
#-----------------------------------------------------------------------------
IPV6_LOOPBACK = IPAddress('::1')

IPV6_PRIVATE = (
    IPNetwork('fc00::/7'),  #   Unique Local Addresses (ULA)
    IPNetwork('fec0::/10'), #   Site Local Addresses (deprecated - RFC 3879)
)

IPV6_LINK_LOCAL = IPNetwork('fe80::/10')

IPV6_MULTICAST = IPNetwork('ff00::/8')

IPV6_RESERVED = (
    IPNetwork('ff00::/12'), IPNetwork('::/8'),
    IPNetwork('0100::/8'), IPNetwork('0200::/7'),
    IPNetwork('0400::/6'), IPNetwork('0800::/5'),
    IPNetwork('1000::/4'), IPNetwork('4000::/3'),
    IPNetwork('6000::/3'), IPNetwork('8000::/3'),
    IPNetwork('A000::/3'), IPNetwork('C000::/3'),
    IPNetwork('E000::/4'), IPNetwork('F000::/5'),
    IPNetwork('F800::/6'), IPNetwork('FE00::/9'),
)