Python ipaddress 模块,IPv6Network() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ipaddress.IPv6Network()

项目:privcount    作者:privcount    | 项目源码 | 文件源码
def validate_ip_network_address_prefix(address, prefix, strict=True):
    '''
    If address/prefix is a valid IP network when parsed according to strict,
    return it as an ipnetwork object.
    Otherwise, return None.
    '''
    ip_address = validate_ip_address(address)
    if ip_address is None or ip_address.version not in [4,6]:
        return None
    try:
        if ip_address.version == 4:
            return ipaddress.IPv4Network((ip_address, prefix), strict=strict)
        else:
            return ipaddress.IPv6Network((ip_address, prefix), strict=strict)
    except ValueError:
        return None
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_cidr_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)

        cur.execute("select null::cidr")
        self.assertTrue(cur.fetchone()[0] is None)

        cur.execute("select '127.0.0.0/24'::cidr")
        obj = cur.fetchone()[0]
        self.assertTrue(isinstance(obj, ip.IPv4Network), repr(obj))
        self.assertEqual(obj, ip.ip_network('127.0.0.0/24'))

        cur.execute("select '::ffff:102:300/128'::cidr")
        obj = cur.fetchone()[0]
        self.assertTrue(isinstance(obj, ip.IPv6Network), repr(obj))
        self.assertEqual(obj, ip.ip_network('::ffff:102:300/128'))
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_cidr_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)

        cur.execute("select null::cidr")
        self.assert_(cur.fetchone()[0] is None)

        cur.execute("select '127.0.0.0/24'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv4Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('127.0.0.0/24'))

        cur.execute("select '::ffff:102:300/128'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv6Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('::ffff:102:300/128'))
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def perform_create(self, serializer, remote_ip):
        captcha = (
                ipaddress.ip_address(remote_ip) not in ipaddress.IPv6Network(os.environ['DESECSTACK_IPV6_SUBNET'])
                and (
                    User.objects.filter(
                        created__gte=timezone.now()-timedelta(hours=settings.ABUSE_BY_REMOTE_IP_PERIOD_HRS),
                        registration_remote_ip=remote_ip
                    ).count() >= settings.ABUSE_BY_REMOTE_IP_LIMIT
                    or
                    User.objects.filter(
                        created__gte=timezone.now() - timedelta(hours=settings.ABUSE_BY_EMAIL_HOSTNAME_PERIOD_HRS),
                        email__endswith=serializer.validated_data['email'].split('@')[-1]
                    ).count() >= settings.ABUSE_BY_EMAIL_HOSTNAME_LIMIT
                )
            )

        user = serializer.save(registration_remote_ip=remote_ip, captcha_required=captcha)
        if user.captcha_required:
            send_account_lock_email(self.request, user)
        elif not user.dyn:
            context = {'token': user.get_token()}
            send_token_email(context, user)
        signals.user_registered.send(sender=self.__class__, user=user, request=self.request)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def test_cidr_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)

        cur.execute("select null::cidr")
        self.assertTrue(cur.fetchone()[0] is None)

        cur.execute("select '127.0.0.0/24'::cidr")
        obj = cur.fetchone()[0]
        self.assertTrue(isinstance(obj, ip.IPv4Network), repr(obj))
        self.assertEqual(obj, ip.ip_network('127.0.0.0/24'))

        cur.execute("select '::ffff:102:300/128'::cidr")
        obj = cur.fetchone()[0]
        self.assertTrue(isinstance(obj, ip.IPv6Network), repr(obj))
        self.assertEqual(obj, ip.ip_network('::ffff:102:300/128'))
项目:nmbs-realtime-feed    作者:datamindedbe    | 项目源码 | 文件源码
def test_cidr_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)

        cur.execute("select null::cidr")
        self.assert_(cur.fetchone()[0] is None)

        cur.execute("select '127.0.0.0/24'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv4Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('127.0.0.0/24'))

        cur.execute("select '::ffff:102:300/128'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv6Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('::ffff:102:300/128'))
项目:OneClickDTU    作者:satwikkansal    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:l3overlay    作者:catalyst    | 项目源码 | 文件源码
def ip_address_get(value):
    '''
    Get an IP address from a string. Raises a GetError if the string
    is not a valid IP address. Supports both IPv4 and IPv6.
    '''

    if isinstance(value, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
        raise GetError(
            "%s not allowed to be converted to IP address, use class attributes" %
            type(value).__name__,
        )

    try:
        return ipaddress.ip_address(value)
    except ValueError:
        raise GetError("value '%s' is not a valid IPv4/IPv6 address" % value)
项目:slack_scholar    作者:xLeitix    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:djangolg    作者:wolcomm    | 项目源码 | 文件源码
def __init__(self, value):
        """Initialise new IPPrefix instance."""
        try:
            obj = ipaddress.ip_address(value)
        except Exception:
            try:
                obj = ipaddress.ip_network(value, strict=False)
            except Exception:
                raise
        if type(obj) in [ipaddress.IPv4Address, ipaddress.IPv6Address]:
            self.prefix = None
            self.type = self.HOST
        elif type(obj) in [ipaddress.IPv4Network, ipaddress.IPv6Network]:
            self.prefix = obj.network_address
            self.type = self.PREFIX
        self.version = obj.version
        self.txt = obj.compressed
项目:RemoteTree    作者:deNULL    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:quickstart-git2s3    作者:aws-quickstart    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value
项目:flask    作者:bobohope    | 项目源码 | 文件源码
def test_cidr_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)

        cur.execute("select null::cidr")
        self.assert_(cur.fetchone()[0] is None)

        cur.execute("select '127.0.0.0/24'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv4Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('127.0.0.0/24'))

        cur.execute("select '::ffff:102:300/128'::cidr")
        obj = cur.fetchone()[0]
        self.assert_(isinstance(obj, ip.IPv6Network), repr(obj))
        self.assertEquals(obj, ip.ip_network('::ffff:102:300/128'))
项目:IP    作者:DannyMcwaves    | 项目源码 | 文件源码
def __init__(self, address: str, mask: int=32):
        """
        :param address: The IP address
        :param mask: this is the mask it should take for the number of hosts that you are planning to access
                      the mask can be a valid host mask or a valid net_mask or a num_digit slash.
                      host mask starts with 0 and contain either 0's and 255's
                      net masks start with 255 and contain either 0's and 255's
        """
        try:
            self.ip_address = Resolve(address)
            self.__mask = mask
            addr = self.ip_address + str(mask)
            self.mask_addr = ipaddress.IPv4Network(addr, strict=False) if self.ip_address.version == "IPv4" else \
                ipaddress.IPv6Network(addr, strict=False)
        except UnResolvedException as unRes:
            print(unRes.args[1])
            sys.exit()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def register_ipaddress(conn_or_curs=None):
    """
    Register conversion support between `ipaddress` objects and `network types`__.

    :param conn_or_curs: the scope where to register the type casters.
        If `!None` register them globally.

    After the function is called, PostgreSQL :sql:`inet` values will be
    converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
    objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
    `~ipaddress.IPv6Network`.

    .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
    """
    global ipaddress
    import ipaddress

    global _casters
    if _casters is None:
        _casters = _make_casters()

    for c in _casters:
        register_type(c, conn_or_curs)

    for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
              ipaddress.IPv4Network, ipaddress.IPv6Network]:
        register_adapter(t, adapt_ipaddress)
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_cidr_array_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)
        cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::cidr[]")
        l = cur.fetchone()[0]
        self.assertTrue(l[0] is None)
        self.assertEqual(l[1], ip.ip_network('127.0.0.1'))
        self.assertEqual(l[2], ip.ip_network('::ffff:102:300/128'))
        self.assertTrue(isinstance(l[1], ip.IPv4Network), l)
        self.assertTrue(isinstance(l[2], ip.IPv6Network), l)
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def register_ipaddress(conn_or_curs=None):
    """
    Register conversion support between `ipaddress` objects and `network types`__.

    :param conn_or_curs: the scope where to register the type casters.
        If `!None` register them globally.

    After the function is called, PostgreSQL :sql:`inet` values will be
    converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
    objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
    `~ipaddress.IPv6Network`.

    .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
    """
    global ipaddress
    import ipaddress

    global _casters
    if _casters is None:
        _casters = _make_casters()

    for c in _casters:
        register_type(c, conn_or_curs)

    for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
              ipaddress.IPv4Network, ipaddress.IPv6Network]:
        register_adapter(t, adapt_ipaddress)
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:prngmgr    作者:wolcomm    | 项目源码 | 文件源码
def __init__(self, prefix=None, strict=False):
        """Init new Prefix instance."""
        if isinstance(prefix, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
            self._prefix = prefix
        else:
            self._prefix = ipaddress.ip_network(prefix, strict=strict)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:archive-Holmes-Totem-Service-Library    作者:HolmesProcessing    | 项目源码 | 文件源码
def Detect(_input):
    """
    Determine the type of the object and return an integer corresponding to the
    global constants Domain, Email, or IP.

    Any string input is assumed to be utf-8 encoded and transformed to a bytes
    object by calling _input.encode("utf-8") if necessary (domain/email
    detection).

    Supports IPv4, IPv6 in punctuated string representation or decimal number
        (<32 bit is considered IPv4)
        -> Return value: ipaddress.IPv4Address or ipaddress.IPv6Address
    Supports CIDR IP address range (returns: ipaddress.IPv4Network or
        ipaddress.IPv6Network)
    Supports Email and "Name <Email>" (returns Email)
    Supports Domain (returns the input string)
    Supports detection of files (by checking if it is available in /tmp/)

    On success returns:

         Type(int): Domain, Email, IP, IPNet, File
         Parsed Object: Email, ipaddress.ip_address, ipaddress.ip_network, os.Fi
         Error: None

    On failure returns:

         Type(int): Unknown / None (None if EmptyInputError)
         Parsed Object: None
         Error: EmptyInputError / UnknownTypeError

    *Any attempt to detect a domain without a proper TLD map set will
    result in a panic!* (see inputtype.InitializeTLDMap(path))

    TODO: provide methods to check if an input is a specific type
    """
    return __detectType(_input)
项目:pytestlab    作者:sangoma    | 项目源码 | 文件源码
def monkey_patch_support_for_python2():
    from future import standard_library
    standard_library.install_aliases()

    # Monkey patch the backported ipaddress module with alternative
    # versions that accept string addresses, in addition to unicode
    # addresses, in python2 code.
    #
    # This keep compatibility simple. Slightly complicated by the fact
    # that some of these classes inherit from each other.
    import ipaddress

    def python2_compat(cls, bases=()):
        def __init__(self, address, *args, **kwargs):
            if isinstance(address, str) and len(address) > 4:
                address = address.decode('utf-8')
            return cls.__init__(self, address, *args, **kwargs)

        return type(cls.__name__, (cls,) + bases, {'__init__': __init__})

    ipaddress.IPv4Network = python2_compat(ipaddress.IPv4Network)
    ipaddress.IPv4Address = python2_compat(ipaddress.IPv4Address)
    ipaddress.IPv4Interface = python2_compat(ipaddress.IPv4Interface,
                                             bases=(ipaddress.IPv4Address,))

    ipaddress.IPv6Network = python2_compat(ipaddress.IPv6Network)
    ipaddress.IPv6Address = python2_compat(ipaddress.IPv6Address)
    ipaddress.IPv6Interface = python2_compat(ipaddress.IPv6Interface,
                                             bases=(ipaddress.IPv6Address,))
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def register_ipaddress(conn_or_curs=None):
    """
    Register conversion support between `ipaddress` objects and `network types`__.

    :param conn_or_curs: the scope where to register the type casters.
        If `!None` register them globally.

    After the function is called, PostgreSQL :sql:`inet` values will be
    converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
    objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
    `~ipaddress.IPv6Network`.

    .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
    """
    global ipaddress
    import ipaddress

    global _casters
    if _casters is None:
        _casters = _make_casters()

    for c in _casters:
        register_type(c, conn_or_curs)

    for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
              ipaddress.IPv4Network, ipaddress.IPv6Network]:
        register_adapter(t, adapt_ipaddress)
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def test_cidr_array_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)
        cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::cidr[]")
        l = cur.fetchone()[0]
        self.assertTrue(l[0] is None)
        self.assertEqual(l[1], ip.ip_network('127.0.0.1'))
        self.assertEqual(l[2], ip.ip_network('::ffff:102:300/128'))
        self.assertTrue(isinstance(l[1], ip.IPv4Network), l)
        self.assertTrue(isinstance(l[2], ip.IPv6Network), l)
项目:nmbs-realtime-feed    作者:datamindedbe    | 项目源码 | 文件源码
def register_ipaddress(conn_or_curs=None):
    """
    Register conversion support between `ipaddress` objects and `network types`__.

    :param conn_or_curs: the scope where to register the type casters.
        If `!None` register them globally.

    After the function is called, PostgreSQL :sql:`inet` values will be
    converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
    objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
    `~ipaddress.IPv6Network`.

    .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
    """
    global ipaddress
    import ipaddress

    global _casters
    if _casters is None:
        _casters = _make_casters()

    for c in _casters:
        register_type(c, conn_or_curs)

    for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
              ipaddress.IPv4Network, ipaddress.IPv6Network]:
        register_adapter(t, adapt_ipaddress)
项目:nmbs-realtime-feed    作者:datamindedbe    | 项目源码 | 文件源码
def test_cidr_array_cast(self):
        import ipaddress as ip
        cur = self.conn.cursor()
        psycopg2.extras.register_ipaddress(cur)
        cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::cidr[]")
        l = cur.fetchone()[0]
        self.assert_(l[0] is None)
        self.assertEquals(l[1], ip.ip_network('127.0.0.1'))
        self.assertEquals(l[2], ip.ip_network('::ffff:102:300/128'))
        self.assert_(isinstance(l[1], ip.IPv4Network), l)
        self.assert_(isinstance(l[2], ip.IPv6Network), l)
项目:packetweaver    作者:ANSSI-FR    | 项目源码 | 文件源码
def get_network_object(prefix):
        u = prefix.decode('utf8')
        try:
            return ipaddress.IPv4Network(u, strict=False)
        except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError):
            pass
        try:
            return ipaddress.IPv6Network(u, strict=False)
        except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError):
            return None
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def setUp(self):
        self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
        self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
        self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
        #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
        self.ipv6_address = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1')
        self.ipv6_interface = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1/64')
        self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testGetSupernet(self):
        self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
        self.assertEqual(str(self.ipv4_network.supernet().network_address),
                         '1.2.2.0')
        self.assertEqual(
            ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
            ipaddress.IPv4Network('0.0.0.0/0'))

        self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
        self.assertEqual(str(self.ipv6_network.supernet().network_address),
                         '2001:658:22a:cafe::')
        self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
                         ipaddress.IPv6Network('::0/0'))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testGetSubnetForSingle128(self):
        ip = ipaddress.IPv6Network('::1/128')
        subnets1 = [str(x) for x in ip.subnets()]
        subnets2 = [str(x) for x in ip.subnets(2)]
        self.assertEqual(subnets1, ['::1/128'])
        self.assertEqual(subnets1, subnets2)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testIpType(self):
        ipv4net = ipaddress.ip_network('1.2.3.4')
        ipv4addr = ipaddress.ip_address('1.2.3.4')
        ipv6net = ipaddress.ip_network('::1.2.3.4')
        ipv6addr = ipaddress.ip_address('::1.2.3.4')
        self.assertEqual(ipaddress.IPv4Network, type(ipv4net))
        self.assertEqual(ipaddress.IPv4Address, type(ipv4addr))
        self.assertEqual(ipaddress.IPv6Network, type(ipv6net))
        self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testExplodeShortHandIpStr(self):
        addr1 = ipaddress.IPv6Interface('2001::1')
        addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
        addr3 = ipaddress.IPv6Network('2001::/96')
        addr4 = ipaddress.IPv4Address('192.168.178.1')
        self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
                         addr1.exploded)
        self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
                         ipaddress.IPv6Interface('::1/128').exploded)
        # issue 77
        self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
                         addr2.exploded)
        self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
                         addr3.exploded)
        self.assertEqual('192.168.178.1', addr4.exploded)
项目:OneClickDTU    作者:satwikkansal    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def _validate_ip_name(self, tree):
        if any(isinstance(name, IPAddress) and not isinstance(
            name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
        ) for name in tree):
            raise TypeError(
                "IPAddress name constraints must be an IPv4Network or"
                " IPv6Network object"
            )