• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python netaddr.IPAddress类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: get_ip_address

    def get_ip_address(self, test_address=None):
        """
        try to get global IP address from interface information.
        if failed, just return '127.0.0.1'

        :param str test_address: ip address str if test to check global ip.
                                  normally None.
        :return: global ip address if successed, or '127.0.0.1'
        """
        for iface_name in netifaces.interfaces():
            iface_data = netifaces.ifaddresses(iface_name)
            logging.debug('Interface: %s' % (iface_name, ))
            ifaces = []
            if netifaces.AF_INET in iface_data:
                ifaces += iface_data[netifaces.AF_INET]
            if netifaces.AF_INET6 in iface_data:
                ifaces += iface_data[netifaces.AF_INET6]
            for iface in ifaces:
                ip = iface['addr']
                ip = re.sub(r'\%.+$', '', ip)
                if test_address is not None:
                    ip = test_address
                addr = IPAddress(ip)
                if not addr.is_loopback() and addr.is_unicast() and\
                   not addr.is_private():
                    logging.debug('global ip %s', addr)
                    return ip
        logging.debug('no global ip')
        return '127.0.0.1'
开发者ID:utamaro,项目名称:StorjNet,代码行数:29,代码来源:encryption.py


示例2: address

 def address(self, value):
     ip = IPAddress(self.ipformat(value))
     if ip.is_loopback():
         raise ValidationError("You cannot use a loopback address")
     if ip.is_multicast():
         raise ValidationError("You cannot use a multicast address")
     self._address = value
开发者ID:moloch--,项目名称:RootTheBox,代码行数:7,代码来源:IpAddress.py


示例3: to_server_dict

def to_server_dict(server):
    public_ips = [ip["addr"] for ip in server.addresses["public"]]
    private_ips = [ip["addr"] for ip in server.addresses["private"]]

    # Pick out first public IPv4 and IPv6 address
    public_ipv4 = None
    public_ipv6 = None

    for ip in public_ips:
        try:
            ip_obj = IPAddress(ip)
        except Exception:
            continue

        if not ip_obj.is_private():
            if ip_obj.version == 4:
                public_ipv4 = ip
            elif ip_obj.version == 6:
                public_ipv6 = ip

    result = {
        "id": server.id,
        "name": server.name,
        "status": server.status,
        "image_id": server.image["id"],
        "flavor_id": server.flavor["id"],
        "public_ips": public_ips,
        "private_ips": private_ips,
        "public_ipv4": public_ipv4,
        "public_ipv6": public_ipv6,
        "key_name": server.key_name,
        "metadata": server.metadata,
    }
    return result
开发者ID:renancaldeira,项目名称:st2contrib,代码行数:34,代码来源:formatters.py


示例4: create_endpoint

def create_endpoint():
    data = request.get_json(force=True)
    app.logger.debug('CreateEndpoint JSON=%s', data)

    endpoint_id = data['EndpointID']
    network_id = data['NetworkID']
    interface = data['Interface']

    app.logger.info('Creating endpoint %s', endpoint_id)

    # docker sent me 172.19.0.3/16 ...
    address_ip4 = interface.get('Address', None)
    if address_ip4 and '/' in address_ip4:
        address_ip4 = IPAddress(address_ip4.split('/', 1)[0])

    network = Network.get(network_id)

    if not network:
        error_message = "CreateEndpoint called but network doesn\'t exist" \
                        " Endpoint ID: %s Network ID: %s" % \
                        (endpoint_id, network_id)
        app.logger.error(error_message)
        raise Exception(error_message)

    network.acquire_ip(endpoint_id, hostname, ip=address_ip4)
    app.logger.debug('CreateEndpoint response JSON=%s', {})
    return jsonify({})
开发者ID:tonicbupt,项目名称:nerub,代码行数:27,代码来源:plugin.py


示例5: validate_ip

    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,代码行数:29,代码来源:middleware.py


示例6: get_priv_info

def get_priv_info(d_iface_to_addr=None):
    s_net_id = None
    s_priv_ip = None
    s_priv_interface = None
    if d_iface_to_addr is None:
        d_iface_to_addr = get_iface_to_addr()
    networks = search('net', 'name', '*')
    for s_iface, d_addr in d_iface_to_addr.items():
        if s_iface.startswith('lo'):
            continue
        if netifaces.AF_INET not in d_addr:
            continue
        ips = d_addr[netifaces.AF_INET]
        for ip in ips:
            o_ip = IPAddress(str(ip['addr']))
            if not o_ip.is_private():
                continue
            if ip['addr'] == '127.0.0.1':
                continue
            for net in networks:
                if (('netmask' in net) and
                        (o_ip in IPNetwork(net['netmask']))):
                    s_priv_ip = str(ip['addr'])
                    s_priv_interface = s_iface
                    s_net_id = net['name']
                    break
    return (s_priv_ip, s_priv_interface, s_net_id)
开发者ID:mdomke,项目名称:srvinv-cli,代码行数:27,代码来源:__init__.py


示例7: encode

    def encode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """Encodes the specified data into an IPAddress object

        :param data: the data to encode into an IPAddress
        :type data: str or raw bytes (BBBB)
        :return: the encoded IPAddress
        """
        if isinstance(data, (str, int)):
            try:
                ip = IPAddress(data)
                if ip is not None and ip.version == 4 and not ip.is_netmask():
                    return ip
            except:
                pass
        try:

            structFormat = ">"
            if endianness == AbstractType.ENDIAN_BIG:
                structFormat = ">"

            if not sign == AbstractType.SIGN_SIGNED:
                structFormat += "bbbb"
            else:
                structFormat += "BBBB"
            quads = map(str, struct.unpack(structFormat, data))
            strIP = string.join(quads, '.')

            ip = IPAddress(strIP)
            if ip is not None and ip.version == 4 and not ip.is_netmask():
                return ip
        except Exception, e:
            raise TypeError("Impossible encode {0} into an IPv4 data ({1})".format(data, e))
开发者ID:chubbymaggie,项目名称:netzob,代码行数:32,代码来源:IPv4.py


示例8: auto_select_target

def auto_select_target(target, output=None):
    """Auto selection logic"""
    print "Target: %s" % target
    try:
        inp=IPAddress(target);
        if inp.is_private() or inp.is_loopback():
            print "Internal IP Detected : Skipping"
            sys.exit()
        else:
            print "Looks like an IP, running ipOsint...\n"
            ipOsint.run(target, output)
    except SystemExit:
        print "exiting"
    except AddrFormatError:
        if re.match('[^@][email protected][^@]+\.[^@]+', target):
            print "Looks like an EMAIL, running emailOsint...\n"
            emailOsint.run(target, output)
        elif get_tld(target, fix_protocol=True,fail_silently=True) is not None:
            print "Looks like a DOMAIN, running domainOsint...\n"
            domainOsint.run(target, output)
        else:
            print "Nothing Matched assuming username, running usernameOsint...\n"
            usernameOsint.run(target, output)
    except:
        print "Unknown Error Occured"
开发者ID:Chan9390,项目名称:datasploit,代码行数:25,代码来源:datasploit.py


示例9: is_valid_netmask

def is_valid_netmask(ip_addr):
    """Valid the format of a netmask"""
    try:
        ip_address = IPAddress(ip_addr)
        return ip_address.is_netmask()

    except Exception:
        return False
开发者ID:SysCompass,项目名称:compass-core,代码行数:8,代码来源:util.py


示例10: call

    def call(self, url, context):
        if self.url_can_resolve(url):
            try:
                ip = yield self.resolver.get_host_by_name(url.domain)
                ip = IPAddress(ip)
            except Exception:
                # context["event"].target.respond(
                #     u'[Error] Failed to handle URL: {}'.format(
                #         url.to_string()
                #     )
                # )

                self.plugin.logger.exception("Error while checking DNS")
                returnValue(STOP_HANDLING)
                return

            if ip.is_loopback() or ip.is_private() or ip.is_link_local() \
                    or ip.is_multicast():
                self.plugin.logger.warn(
                    "Prevented connection to private/internal address"
                )

                returnValue(STOP_HANDLING)
                return

        headers = {}

        if url.domain in context["config"]["spoofing"]:
            user_agent = context["config"]["spoofing"][url.domain]

            if user_agent:
                headers["User-Agent"] = user_agent
        else:
            headers["User-Agent"] = context["config"].get(
                "default_user_agent",
                "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 "
                "Firefox/36.0"
            )

        domain_langs = context.get("config") \
            .get("accept_language", {}) \
            .get("domains", {})

        if url.domain in domain_langs:
            headers["Accept-Language"] = domain_langs.get(url.domain)
        else:
            headers["Accept-Language"] = context.get("config") \
                .get("accept_language", {}) \
                .get("default", "en")

        session = self.get_session(url, context)
        session.get(unicode(url), headers=headers, stream=True,
                    background_callback=self.background_callback) \
            .addCallback(self.callback, url, context, session) \
            .addErrback(self.errback, url, context, session)

        returnValue(STOP_HANDLING)
开发者ID:UltrosBot,项目名称:Ultros,代码行数:57,代码来源:website.py


示例11: reload

	def reload(self):
		self._nameservers = []
		ns = self._service.nameserversConfig()
		for n in ns:
			ip = IPAddress(n)
			if ip.version == 4:
				cfg = ConfigIP( default=toIP4List(ip.format()))
				self._nameservers.append(cfg)
			elif ip.version == 6:
				cfg = ConfigIP6(default=ip.format())
				self._nameservers.append(cfg)
开发者ID:OpenDMM,项目名称:enigma2,代码行数:11,代码来源:NetworkConfig.py


示例12: _normalize_ip_address

    def _normalize_ip_address(addr):
        """
        When we used mapped ipv4 (starting with ::FFFF/96) we need to
        normalize it to ipv4 in order to compare it with value used
        in commonName in the certificate.
        """
        ip = IPAddress(addr)
        if ip.is_ipv4_mapped():
            addr = str(ip.ipv4())

        return addr
开发者ID:EdDev,项目名称:vdsm,代码行数:11,代码来源:sslutils.py


示例13: test_ipaddress_v6

def test_ipaddress_v6():
    ip = IPAddress('fe80::dead:beef')
    assert ip.version == 6
    assert repr(ip) == "IPAddress('fe80::dead:beef')"
    assert str(ip) == 'fe80::dead:beef'
    assert ip.format() == 'fe80::dead:beef'
    assert int(ip) == 338288524927261089654018896845083623151
    assert hex(ip) == '0xfe8000000000000000000000deadbeef'
    assert ip.bin == '0b11111110100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011011110101011011011111011101111'
    assert ip.bits() == '1111111010000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:1101111010101101:1011111011101111'
    assert ip.words == (65152, 0, 0, 0, 0, 0, 57005, 48879)
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:11,代码来源:test_ip_v6.py


示例14: test_ipaddress_v4

def test_ipaddress_v4():
    ip = IPAddress('192.0.2.1')
    assert ip.version == 4
    assert repr(ip) == "IPAddress('192.0.2.1')"
    assert str(ip) == '192.0.2.1'
    assert ip.format() == '192.0.2.1'
    assert int(ip) == 3221225985
    assert hex(ip) == '0xc0000201'
    assert ip.bin == '0b11000000000000000000001000000001'
    assert ip.bits() == '11000000.00000000.00000010.00000001'
    assert ip.words == (192, 0, 2, 1)
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:11,代码来源:test_ip_v4.py


示例15: get_version

def get_version(request):
    func = request.GET.get('func', '')
    remote_addr = IPAddress(request.remote_addr)
    data = {
        'address': remote_addr.format(),
        'version': remote_addr.version,
        'ipv4_mapped': remote_addr.is_ipv4_mapped(),
    }
    return Response(
            body='%s(%s);' % (func, json.dumps(data)),
            content_type='text/javascript')
开发者ID:yosida95,项目名称:ipv4-ipv6.yosida95-com,代码行数:11,代码来源:views.py


示例16: normalize_mapped_address

def normalize_mapped_address(ipaddr):
    """
    Converts a IPv4-mapped IPv6 address into a IPv4 address. Handles both the
    ::ffff:192.0.2.128 format as well as the deprecated ::192.0.2.128 format.

    :param ipaddr: IP address [str]
    :return: normalized IP address [str]
    """
    ipaddr = IPAddress(ipaddr)
    if ipaddr.is_ipv4_compat() or ipaddr.is_ipv4_mapped():
        ipaddr = ipaddr.ipv4()
    return str(ipaddr)
开发者ID:FreeMinded,项目名称:nsupdate.info,代码行数:12,代码来源:iptools.py


示例17: ipv4_to_cidr

 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,代码行数:12,代码来源:network_address.py


示例18: validate_ip

    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,代码行数:13,代码来源:middleware.py


示例19: test_01_add_ip_same_cidr

 def test_01_add_ip_same_cidr(self):
     """Test add guest ip range in the existing cidr
     """
     # call increment_cidr function to get exiting cidr from the setup and
     # increment it
     ip2 = self.increment_cidr()
     test_nw = ip2.network
     ip = IPAddress(test_nw)
     # Add IP range(5 IPs) in the new CIDR
     test_gateway = ip.__add__(1)
     test_startIp = ip.__add__(3)
     test_endIp = ip.__add__(10)
     test_startIp2 = ip.__add__(11)
     test_endIp2 = ip.__add__(15)
     # Populating services with new IP range
     self.services["vlan_ip_range"]["startip"] = test_startIp
     self.services["vlan_ip_range"]["endip"] = test_endIp
     self.services["vlan_ip_range"]["gateway"] = test_gateway
     self.services["vlan_ip_range"]["netmask"] = self.netmask
     self.services["vlan_ip_range"]["zoneid"] = self.zone.id
     self.services["vlan_ip_range"]["podid"] = self.pod.id
     # create new vlan ip range
     self.debug("Creating new ip range with new cidr in the same vlan")
     new_vlan = PublicIpRange.create(
         self.apiclient,
         self.services["vlan_ip_range"])
     self.debug(
         "Created new vlan range with startip:%s and endip:%s" %
         (test_startIp, test_endIp))
     self.cleanup.append(new_vlan)
     new_vlan_res = new_vlan.list(self.apiclient, id=new_vlan.vlan.id)
     # Compare list output with configured values
     self.verify_vlan_range(new_vlan_res, self.services["vlan_ip_range"])
     # Add few more ips in the same CIDR
     self.services["vlan_ip_range"]["startip"] = test_startIp2
     self.services["vlan_ip_range"]["endip"] = test_endIp2
     self.debug("Creating new ip range in the existing CIDR")
     new_vlan2 = PublicIpRange.create(
         self.apiclient,
         self.services["vlan_ip_range"])
     self.debug(
         "Created new vlan range with startip:%s and endip:%s" %
         (test_startIp2, test_endIp2))
     self.cleanup.append(new_vlan2)
     # list new vlan ip range
     new_vlan2_res = new_vlan2.list(self.apiclient, id=new_vlan2.vlan.id)
     # Compare list output with configured values
     self.verify_vlan_range(new_vlan2_res, self.services["vlan_ip_range"])
     return
开发者ID:Accelerite,项目名称:cloudstack,代码行数:49,代码来源:test_multiple_ip_ranges.py


示例20: is_valid_gateway

def is_valid_gateway(ip_addr):
    """Valid the format of gateway"""

    invalid_ip_prefix = ['0', '224', '169', '127']
    try:
        # Check if ip_addr is an IP address and not start with 0
        ip_addr_prefix = ip_addr.split('.')[0]
        if is_valid_ip(ip_addr) and ip_addr_prefix not in invalid_ip_prefix:
            ip_address = IPAddress(ip_addr)
            if not ip_address.is_multicast():
                # Check if ip_addr is not multicast and reserved IP
                return True
        return False
    except Exception:
        return False
开发者ID:SysCompass,项目名称:compass-core,代码行数:15,代码来源:util.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python netaddr.IPNetwork类代码示例发布时间:2022-05-27
下一篇:
Python netaddr.valid_mac函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap