当前位置: 首页>>代码示例>>Python>>正文


Python IPNetwork.prefixlen方法代码示例

本文整理汇总了Python中netaddr.IPNetwork.prefixlen方法的典型用法代码示例。如果您正苦于以下问题:Python IPNetwork.prefixlen方法的具体用法?Python IPNetwork.prefixlen怎么用?Python IPNetwork.prefixlen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netaddr.IPNetwork的用法示例。


在下文中一共展示了IPNetwork.prefixlen方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def validate_ip(self, request, remote_ip):
        # When we aren't configured to restrict on IP address
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True
        # When the IP address key hasn't yet been set on the request session
        if SESSION_IP_KEY not in request.session:
            return True
        # When there is no remote IP, check if one has been set on the session
        session_ip = request.session[SESSION_IP_KEY]
        if not remote_ip:
            if session_ip:  # session has remote IP value so validate :-(
                return False
            else:  # Session doesn't have remote IP value so possibly :-)
                return True

        # Compute fuzzy IP compare based on settings on compare sensitivity
        session_network = IPNetwork(session_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
开发者ID:erikr,项目名称:django-restricted-sessions,代码行数:31,代码来源:middleware.py

示例2: ipv4_to_cidr

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
 def ipv4_to_cidr(address, netmask=None, prefixlen=None):
     a = IPAddress(address)
     n = IPNetwork(a)
     if netmask:
         assert prefixlen is None, 'Cannot provide both netmask and prefixlen'
         m = IPAddress(netmask)
         assert m.is_netmask(), 'A valid netmask is required' 
         n.prefixlen = m.netmask_bits() 
     else:
         assert prefixlen, 'Provide either netmask or prefixlen'
         n.prefixlen = int(prefixlen)
     return str(n.cidr)
开发者ID:PublicaMundi,项目名称:ansible-plugins,代码行数:14,代码来源:network_address.py

示例3: validate_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def validate_ip(self, request, remote_ip):
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True) or not SESSION_IP_KEY in request.session:
            return True

        session_network = IPNetwork(request.session[SESSION_IP_KEY])
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
        return remote_ip in session_network
开发者ID:koirikivi,项目名称:django-restricted-sessions,代码行数:15,代码来源:middleware.py

示例4: calculate_vip_start

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def calculate_vip_start(self, vip_start, mgmtip, selfip_external):
        if not selfip_external and not vip_start:
            LOG.info('Skipping auto VIP generation.')
            return

        if selfip_external:
            if not isinstance(selfip_external, IPNetwork):
                selfip_external = IPNetwork(selfip_external)

            if selfip_external.prefixlen == 32:
                    LOG.info('Self IP external has no prefix. Assuming /16.')
                    selfip_external.prefixlen = 16

        if vip_start is None:
            # '1.1.1.1/24' -> '1.1.1.0/24'
            cidr = "{0.network}/{0.prefixlen}".format(mgmtip)
            host_id = mgmtip.ip.value - mgmtip.network.value
            subnet_index = SUBNET_MAP.get(cidr)

            if subnet_index is None:
                LOG.warning('The %s subnet was not found! '
                            'Skipping Virtual Servers.' % cidr)
                return

            # Start from 10.11.50.0 - 10.11.147.240 (planned for 10 subnets, 8 VIPs each)
            offset = 1 + 50 * 256 + DEFAULT_VIPS * (256 * subnet_index + host_id)

            vip_start = selfip_external.network + offset
        else:
            vip_start = IPAddress(vip_start)
        return vip_start
开发者ID:pombredanne,项目名称:f5test2,代码行数:33,代码来源:placer.py

示例5: validate_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def validate_ip(self, request, remote_ip):
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True) or not SESSION_IP_KEY in request.session:
            return True

        session_network = IPNetwork(request.session[SESSION_IP_KEY])
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = IPV4_LENGTH
        except AddrConversionError:
            try:
                session_network.prefixlen = IPV6_LENGTH
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
开发者ID:askoretskiy,项目名称:django-restricted-sessions,代码行数:19,代码来源:middleware.py

示例6: get_admin_ip_w_prefix

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def get_admin_ip_w_prefix(node):
        """Getting admin ip and assign prefix from admin network."""
        network_manager = objects.Node.get_network_manager(node)
        admin_ip = network_manager.get_admin_ip_for_node(node)
        admin_ip = IPNetwork(admin_ip)

        # Assign prefix from admin network
        admin_net = IPNetwork(network_manager.get_admin_network_group().cidr)
        admin_ip.prefixlen = admin_net.prefixlen

        return str(admin_ip)
开发者ID:sk4lf,项目名称:fuel-web,代码行数:13,代码来源:deployment_serializers.py

示例7: get_admin_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def get_admin_ip(cls, node):
        """Getting admin ip and assign prefix from admin network."""
        network_manager = NetworkManager()
        admin_ip = network_manager.get_admin_ips_for_interfaces(
            node)[node.admin_interface.name]
        admin_ip = IPNetwork(admin_ip)

        # Assign prefix from admin network
        admin_net = IPNetwork(network_manager.get_admin_network().cidr)
        admin_ip.prefixlen = admin_net.prefixlen

        return str(admin_ip)
开发者ID:andrey-borisov,项目名称:fuel-web,代码行数:14,代码来源:deployment_serializers.py

示例8: __discover_subnet

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def __discover_subnet(self):
        """
        Creates subnet with prefix /24 for IP that not match with an existent one
        """
        for host in self.hosts:
            if host in self.exclusion:
                continue

            host = IPAddress(host)

            if self.__is_subnet_exists(host):
                continue

            subnet = IPNetwork(host)
            subnet.prefixlen = 24

            # Remove the host part
            subnet = IPNetwork(subnet.network)
            subnet.prefixlen = 24

            self.subnets[subnet] = None

        self.subnets = OrderedDict(sorted(self.subnets.items(), key=lambda network: network[0].prefixlen, reverse=True))
开发者ID:dynamicdeploy,项目名称:sirano,代码行数:25,代码来源:ip.py

示例9: same_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def same_ip(cls, orig_remote_ip, remote_ip):
        # Check is disabled -- always return true
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True

        # No original IP or current IP is unknown
        if not orig_remote_ip or not remote_ip:
            return True

        session_network = IPNetwork(orig_remote_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False

        # IP belongs to the same network
        return remote_ip in session_network
开发者ID:webrunners,项目名称:django-restricted-sessions,代码行数:26,代码来源:middleware.py

示例10: ip4to6

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
def ip4to6(ipv4, prefix=None, base=BASE_IPV6):
    """
    Convert an IPv4 to IPv6 by splitting the network part of the ip and shifting
    it to the Global ID and Subnet ID zone.

    @param address: IPv4 address (e.g. '172.27.58.1/24' or '10.10.0.1/16'
    @type address: str
    @param base: IPv6 reserved base. Default: 'FD32:00F5:0000::'
    @type base: str
    """
    ipv4 = IPNetwork(ipv4)
    if prefix:
        ipv4.prefixlen = prefix
    ipv6 = IPNetwork(BASE_IPV6)
    ipv6.value += (ipv4.value >> (32 - ipv4.prefixlen)) << 64
    ipv6.value += ipv4.value - ipv4.network.value
    return ipv6.ip if prefix else ipv6
开发者ID:pombredanne,项目名称:f5test2,代码行数:19,代码来源:net.py

示例11: modify_subnet

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
    def modify_subnet(self, host, prefixlen):
        """
        Update the calico node resource to use the specified prefix length.

        Returns the current mask size.
        """
        node = json.loads(host.calicoctl(
            "get node %s --output=json" % host.get_hostname()))
        assert len(node) == 1

        # Get the current network and prefix len
        ipnet = IPNetwork(node[0]["spec"]["bgp"]["ipv4Address"])
        current_prefix_len = ipnet.prefixlen

        # Update the prefix length
        ipnet.prefixlen = prefixlen
        node[0]["spec"]["bgp"]["ipv4Address"] = str(ipnet)

        # Write the data back again.
        host.writejson("new_data", node)
        host.calicoctl("apply -f new_data")
        return current_prefix_len
开发者ID:alagalah,项目名称:calico,代码行数:24,代码来源:test_ipip.py

示例12: process_NetworkIPs

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
	def process_NetworkIPs(self):
		self.inv_cache = 0
		self.vc = valid_cache(self.cache_file, self.cache_ttl)
		if self.cache_ttl > 0 and self.vc != 0:
			Log.i('Loading network cache from %s' %(self.cache_file))
			try:
				self.networklist = load_cache(self.cache_file)
				if len(self.networklist) > 0:
					self.updateNetworkList()
				else:
					self.setStatus('error')
			except:
				self.inv_cache = 1
		if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
			Log.i('Getting fresh network list')

			net = IPNetwork('%s/%s' % (self._ipv4.address, self._ipv4.netmask))
			if net.prefixlen < 24:
				net.prefixlen = 24

			self.networklist = []
			self._startScan(self.iface, net.cidr)
开发者ID:dpuschek,项目名称:enigma2-plugins,代码行数:24,代码来源:NetworkBrowser.py

示例13: process_packet

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]

#.........这里部分代码省略.........
                else:
                        # If we don't understand the protocol skip to the next package
                        return

        except AttributeError:
                print('Raised AttributeError when reading ports from package:')
                print(p.summary())
                return

        except IntegrityError:
                # Since get_or_create is not thread-safe,
                # we ignore attempts to create duplicate entries
                pass

        # Find DNS records
        if p[2].sport == 53:
                try:
                        updated_values_dnscache = { "name" : p[6].rrname,
                                                    "last_seen" : timezone.now() }

                        DNScache.objects.update_or_create( address_inet=p[6].rdata,
                                                           defaults=updated_values_dnscache )
                except AttributeError:
                        print('Raised AttributeError when reading DNS answer from package:')
                        print(p.summary())

                except TypeError:
                        print('Raised TypeError when reading DNS answer from package:')
                        print(p.summary())

                except IndexError:
                        # This was not a DNSRR. Disregard.
                        pass

        # Find DHCP ACKs
        if p[2].sport == 67:
                try:
                        if p[4].options[0][1] == 5: # DHCP ACK
                                ip_network = IPNetwork(p[1].dst)
                                ip_network.prefixlen=sum(
                                        [bin(int(x)).count('1') for x in p[4].options[5][1].split('.')] )

                                gateway, new_gateway = Interface.objects.get_or_create(
                                                                address_inet=p[4].options[7][1],
                                                                net=Net.objects.all()[0] )

                                name_server, new_name_server = Interface.objects.get_or_create(
                                                                address_inet=p[4].options[8][1],
                                                                net=Net.objects.all()[0] )

                                updated_values_net = { 'mask_inet' : p[4].options[5][1],
                                                       'address_bcast' : p[4].options[6][1],
                                                       'gateway' : gateway,
                                                       'name_server' : name_server }
                               
                                our_net, new_net = Net.objects.update_or_create(
                                                        address_inet=str(ip_network.network),
                                                        defaults=updated_values_net )
                except AttributeError:
                        print('Raised AttributeError when reading DHCP ACK from package:')
                        print(p.show())

        # Update the connections
        try:
                con = Connection.objects.get( src_socket=src_socket,
                                              dst_socket=dst_socket,
                                              protocol_l567=p.proto )

                if p.proto == 6: # Check if this is a TCP connection 
                        setattr(con, 'seq', p.seq)

                setattr(con, 'tx_pkts', con.tx_pkts + 1)
                setattr(con, 'tx_bytes', con.tx_bytes + p.len)

                con.save()
                new_con = False

        except Connection.DoesNotExist:
                if p.proto==6:
                        con = Connection.objects.create( src_socket=src_socket,
                                                         dst_socket=dst_socket,
                                                         protocol_l567=p.proto,
                                                         first_seen=timezone.now(),
                                                         seq=p.seq )
                else:
                        con = Connection.objects.create( src_socket=src_socket,
                                                 dst_socket=dst_socket,
                                                 protocol_l567=p.proto,
                                                 first_seen=timezone.now() )

                new_con = True

        except IntegrityError:
                # Since we are not thread-safe,
                # we ignore attempts to create duplicate entries
                pass

        except Connection.MultipleObjectsReturned:
                # This shouldn't happen, but in case it does we will skip to the next package
                return
开发者ID:raspispass,项目名称:pythos,代码行数:104,代码来源:tasks.py

示例14: addr

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import prefixlen [as 别名]
 def addr(self, address, prefix):
     ip = IPNetwork(address)
     ip.prefixlen = int(prefix)
     return ip
开发者ID:52-41-4d,项目名称:GreyFiber,代码行数:6,代码来源:layer3.py


注:本文中的netaddr.IPNetwork.prefixlen方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。