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


Python netaddr.IPAddress类代码示例

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


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


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