Пример #1
0
    def test_cidr_ranges(self):
        """Check that CIDR ranges are correctly identified."""
        cidr_range = CidrMatch.to_range("10.0.0.0/8")
        self.assertListEqual(list(cidr_range), [(10, 0, 0, 0),
                                                (10, 255, 255, 255)])
        cidr_range = CidrMatch.to_range("123.45.67.189/32")
        self.assertListEqual(list(cidr_range), [(123, 45, 67, 189),
                                                (123, 45, 67, 189)])

        cidr_range = CidrMatch.to_range("0.0.0.0/0")
        self.assertListEqual(list(cidr_range), [(0, 0, 0, 0),
                                                (255, 255, 255, 255)])

        cidr_range = CidrMatch.to_range("192.168.15.2/22")
        self.assertListEqual(list(cidr_range), [(192, 168, 12, 0),
                                                (192, 168, 15, 255)])
Пример #2
0
    def test_cidr_regex(self):
        """Test that octet regex are correctly matching the range."""
        for _ in range(200):
            # make an ip address
            ip_addr = (
                random.randrange(256),
                random.randrange(256),
                random.randrange(256),
                random.randrange(256),
            )
            size = random.randrange(33)
            total_ips = 2**(32 - size)

            args = list(ip_addr)
            args.append(size)
            cidr_mask = "{:d}.{:d}.{:d}.{:d}/{:d}".format(*args)

            pattern = CidrMatch.make_cidr_regex(cidr_mask)

            regex = re.compile("^({})$".format(pattern))
            min_ip, max_ip = CidrMatch.to_range(cidr_mask)

            # randomly pick IPs that *are* in the range
            for _ in range(min(200, total_ips)):
                rand_addr = [
                    random.randrange(mn, mx + 1)
                    for mn, mx in zip(min_ip, max_ip)
                ]
                rand_ip = "{:d}.{:d}.{:d}.{:d}".format(*rand_addr)

                self.assertIsNotNone(regex.match(rand_ip))

            # todo: pick IPs that are definitely not in the range
            for _ in range(200):
                rand_addr = [random.randrange(0, 255) for _ in range(4)]
                in_subnet = all(
                    mn <= o <= mx
                    for o, mn, mx in zip(rand_addr, min_ip, max_ip))
                rand_ip = "{:d}.{:d}.{:d}.{:d}".format(*rand_addr)

                rv = regex.match(rand_ip) is not None
                self.assertEqual(rv, in_subnet)