Login

CIDR compatible INTERNAL_IPS with Python 3 Standard Library

Author:
yklim
Posted:
January 27, 2018
Language:
Python
Version:
Not specified
Tags:
debug-toolbar INTERNAL_IPS CIDR
Score:
1 (after 1 ratings)

use only in a dev environment.

  • requirement: Python 3.3+
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import Iterable
from ipaddress import IPv4Address, IPv4Network

class IpList(object):
    def __init__(self, addresses):
        self.addresses = [IPv4Network(address) if isinstance(address, Iterable) else IPv4Address(address) for address in addresses]

    def __contains__(self, ip):
        ip = IPv4Address(ip)
        for address in self.addresses:
            if isinstance(address, IPv4Address):
                if ip == address:
                    return True
            if isinstance(address, IPv4Network):
                if ip in address:
                    return True
        return False

INTERNAL_IPS = IpList([
    '127.0.0.1',
    '192.168.0.0/24'
    ])

More like this

Comments

Please login first before commenting.