當前位置: 首頁>>代碼示例>>Python>>正文


Python ipaddress.ip_address方法代碼示例

本文整理匯總了Python中ipaddress.ip_address方法的典型用法代碼示例。如果您正苦於以下問題:Python ipaddress.ip_address方法的具體用法?Python ipaddress.ip_address怎麽用?Python ipaddress.ip_address使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ipaddress的用法示例。


在下文中一共展示了ipaddress.ip_address方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: waf_update_ip_set

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def waf_update_ip_set(ip_set_id, source_ip):
    logging.getLogger().debug('[waf_update_ip_set] Start')

    ip_type = "IPV%s"%ip_address(source_ip).version
    ip_class = "32" if ip_type == "IPV4" else "128"
    waf.update_ip_set(IPSetId=ip_set_id,
        ChangeToken=waf.get_change_token()['ChangeToken'],
        Updates=[{
            'Action': 'INSERT',
            'IPSetDescriptor': {
                'Type': ip_type,
                'Value': "%s/%s"%(source_ip, ip_class)
            }
        }]
    )

    logging.getLogger().debug('[waf_update_ip_set] End') 
開發者ID:awslabs,項目名稱:aws-waf-security-automations,代碼行數:19,代碼來源:access-handler.py

示例2: is_payfast_ip_address

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def is_payfast_ip_address(ip_address_str):
    """
    Return True if ip_address_str matches one of PayFast's server IP addresses.

    Setting: `PAYFAST_IP_ADDRESSES`

    :type ip_address_str: str
    :rtype: bool
    """
    # TODO: Django system check for validity?
    payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
                                   conf.DEFAULT_PAYFAST_IP_ADDRESSES)

    if sys.version_info < (3,):
        # Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
        # (On Python 3, this should generally not happen:
        #  let unexpected bytes values fail as expected.)
        ip_address_str = unicode(ip_address_str)  # noqa: F821
        payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses]  # noqa: F821

    return any(ip_address(ip_address_str) in ip_network(payfast_address)
               for payfast_address in payfast_ip_addresses) 
開發者ID:PiDelport,項目名稱:django-payfast,代碼行數:24,代碼來源:forms.py

示例3: checkIP

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def checkIP(self, directive, directiveValues, findings):
        csp = self.csp
        for value in directiveValues:
            url = '//' + Util.getSchemeFreeUrl(value)
            host = urlparse(url).netloc
            ip = None
            validip = True
            
            try:
                ip = ipaddress.ip_address(u''+host)
            except ValueError:
                validip = False
            if validip:
                ipString = str(ip) + ''
                
                if '127.0.0.1' in ipString:
                    findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive allows localhost as source. Please make sure to remove this in production environments.',FindingSeverity.INFO, directive, value))
                else:
                    findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive has an IP-Address as source: ' + ipString + ' (will be ignored by browsers!). ', FindingSeverity.INFO, directive, value)) 
開發者ID:koenbuyens,項目名稱:securityheaders,代碼行數:21,代碼來源:cspcheck_ipsource.py

示例4: bind_socket

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
    """Create TCP server socket.
    :param host: IPv4, IPv6 or hostname may be specified
    :param port: TCP port number
    :param backlog: Maximum number of connections to queue
    :return: socket.socket object
    """
    try:  # IP address: family must be specified for IPv6 at least
        ip = ip_address(host)
        host = str(ip)
        sock = socket.socket(
            socket.AF_INET6 if ip.version == 6 else socket.AF_INET
        )
    except ValueError:  # Hostname, may become AF_INET or AF_INET6
        sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock 
開發者ID:huge-success,項目名稱:sanic,代碼行數:21,代碼來源:server.py

示例5: get_cidr

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def get_cidr(iplist):
    cidrs = []
    for ip in iplist:
        cidr = re.sub(r'\d+$', '0/24', ip)
        cidrs.append(ipaddress.ip_network(cidr))

    result = []

    for cidr in cidrs:
        for i in iplist:
            ip = ipaddress.ip_address(i)
            if ip in cidr:
                result.append(str(cidr))
                break
    out = get_top(result)
    for i in out:
        cidr, num = i.split('|')
        print(cidr, num) 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:20,代碼來源:analyzer.py

示例6: iscdn

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def iscdn(host):
    result = True
    # noinspection PyBroadException
    try:
        if not re.search(r'\d+\.\d+\.\d+\.\d+', host):
            host = parse_ip(host)
        for cdn in cdns:
            if ipaddress.ip_address(host) in ipaddress.ip_network(cdn):
                result = False
    except Exception:
        pass

    # noinspection PyBroadException
    try:
        with geoip2.database.Reader('data/GeoLite2-ASN.mmdb') as reader:
            response = reader.asn(host)
            for i in ASNS:
                if response.autonomous_system_number == int(i):
                    result = False
    except Exception:
        pass
    return result 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:24,代碼來源:iscdn.py

示例7: raw

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def raw(self, arch=None):
        if not arch:
            raise ValueError("Architecture must be specified.")

        the_arch = convert_arch(arch)

        if the_arch.name != "MIPS32":
            raise TypeError("%s only supports MIPS32." % str(self.__class__))

        packed_port = struct.pack('>H', (~self.port) & 0xffff)

        target_ip = socket.gethostbyname(self.host)
        ip = ipaddress.ip_address(target_ip)
        ip_for_shellcode = (~int(ip)) & 0xffffffff

        ip_to_send = struct.pack('>I', ip_for_shellcode)
        lower_ip = ip_to_send[:2]
        higher_ip = ip_to_send[2:]

        if the_arch.memory_endness == Endness.LE:
            return self.code_le % (packed_port, higher_ip, lower_ip)
        else:
            raise NOTIMPLEMENTEDYET() 
開發者ID:angr,項目名稱:rex,代碼行數:25,代碼來源:linux_mips32_connectback.py

示例8: _is_url_naive

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def _is_url_naive(urlstr: str) -> bool:
    """Naive check if given URL is really a URL.

    Args:
        urlstr: The URL to check for, as string.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    url = qurl_from_user_input(urlstr)
    assert url.isValid()
    host = url.host()

    # Valid IPv4/IPv6 address. Qt converts things like "23.42" or "1337" or
    # "0xDEAD" to IP addresses, which we don't like, so we check if the host
    # from Qt is part of the input.
    if (not utils.raises(ValueError, ipaddress.ip_address, host) and
            host in urlstr):
        return True

    tld = r'\.([^.0-9_-]+|xn--[a-z0-9-]+)$'
    forbidden = r'[\u0000-\u002c\u002f\u003a-\u0060\u007b-\u00b6]'
    return bool(re.search(tld, host) and not re.search(forbidden, host)) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:25,代碼來源:urlutils.py

示例9: get_request_ip

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def get_request_ip(request: Any, context: Optional[Dict] = None) -> Optional[str]:
        if request._cache.get('request_ip'):
            return str(request._cache.get('request_ip', ''))

        if request.transport:
            if not context:
                context = {}
            real_ip_header = context.get('options', {}).get('http', {}).get('real_ip_header', 'X-Forwarded-For')
            real_ip_from = context.get('options', {}).get('http', {}).get('real_ip_from', [])
            if isinstance(real_ip_from, str):
                real_ip_from = [real_ip_from]

            peername = request.transport.get_extra_info('peername')
            request_ip = None
            if peername:
                request_ip, _ = peername
            if real_ip_header and real_ip_from and request.headers.get(real_ip_header) and request_ip and len(real_ip_from):
                if any([ipaddress.ip_address(request_ip) in ipaddress.ip_network(cidr) for cidr in real_ip_from]):
                    request_ip = request.headers.get(real_ip_header).split(',')[0].strip().split(' ')[0].strip()

            request._cache['request_ip'] = request_ip
            return request_ip

        return None 
開發者ID:kalaspuff,項目名稱:tomodachi,代碼行數:26,代碼來源:http.py

示例10: setup_kubernetes_client

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def setup_kubernetes_client():
    if config.CONF.kubernetes.api_root:
        api_root = config.CONF.kubernetes.api_root
    else:
        # NOTE(dulek): This is for containerized deployments, i.e. running in
        #              K8s Pods.
        host = os.environ['KUBERNETES_SERVICE_HOST']
        port = os.environ['KUBERNETES_SERVICE_PORT_HTTPS']
        try:
            addr = ipaddress.ip_address(host)
            if addr.version == 6:
                host = '[%s]' % host
        except ValueError:
            # It's not an IP addres but a hostname, it's fine, move along.
            pass
        api_root = "https://%s:%s" % (host, port)
    _clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(api_root) 
開發者ID:openstack,項目名稱:kuryr-kubernetes,代碼行數:19,代碼來源:clients.py

示例11: _match_whitelist

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def _match_whitelist(self, address: str, whitelist: str) -> bool:
        trimmed_address = re.sub(r"/32$", "", address)
        if address in whitelist:
            raise PluginException(
                cause=f"Address Object not created because the host {address} was found in the whitelist as {address}.",
                assistance=f"If you would like to block this host, remove {address} from the whitelist and try again.")
        elif '/' not in trimmed_address:
            pass

        for address_object in whitelist:
            if self._determine_address_type(address_object) == "cidr":
                net = ip_network(address_object, False)
                ip = ip_address(trimmed_address)
                if ip in net:
                    raise PluginException(
                        cause=f"Address Object not created because the host {address}"
                              f" was found in the whitelist as {address_object}.",
                        assistance="If you would like to block this host,"
                              f" remove {address_object} from the whitelist and try again.")

        return False 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:23,代碼來源:action.py

示例12: find_internal_ip_on_device_network

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
    """
    For a given UPnP device, return the internal IP address of this host machine that can
    be used for a NAT mapping.
    """
    parsed_url = urlparse(upnp_dev.location)
    # Get an ipaddress.IPv4Network instance for the upnp device's network.
    upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False)
    for iface in netifaces.interfaces():
        for family, addresses in netifaces.ifaddresses(iface).items():
            # TODO: Support IPv6 addresses as well.
            if family != netifaces.AF_INET:
                continue
            for item in addresses:
                if ipaddress.ip_address(item["addr"]) in upnp_dev_net:
                    return item["addr"]
    raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname) 
開發者ID:QuarkChain,項目名稱:pyquarkchain,代碼行數:19,代碼來源:nat.py

示例13: fetch_peers_async

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def fetch_peers_async(node):
    """
    :param node: tuple(ip, p2p_port, jrpc_port)
    :return: list of tuple(ip, p2p_port, jrpc_port)
    """
    json_rpc_url = "http://{}:{}".format(node[0], node[2])
    server = Server(json_rpc_url)
    try:
        peers = await asyncio.wait_for(server.get_peers(), 5)
    except Exception:
        print("Failed to get peers from {}".format(json_rpc_url))
        peers = {"peers": []}
    await server.session.close()
    return [
        (
            str(ipaddress.ip_address(int(p["ip"], 16))),
            int(p["port"], 16),
            int(p["port"], 16) + node[2] - node[1],
        )
        for p in peers["peers"]
    ] 
開發者ID:QuarkChain,項目名稱:pyquarkchain,代碼行數:23,代碼來源:monitoring.py

示例14: transform_index_ipv6_address

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def transform_index_ipv6_address(ipv6_str):
    """
    Converts a substring of an SNMP index that contains an IPv6 address into a human readable format.
    Example:
        254.128.0.0.0.0.0.0.14.134.16.255.254.243.135.30 => fe80::e86:10ff:fef3:871e
    Args:
        ipv6_str (str): SNMP index substring containing an IPv6 address.
    Returns:
        str: human readable IPv6 address
    """
    parts = [u"{0:02x}".format(int(x)) for x in ipv6_str.split(u'.')]
    byte_string = u""
    for p, i in enumerate(parts):
        if p % 2 != 0:
            byte_string += u'{}{}:'.format(parts[p - 1].lstrip(u'0'), parts[p])

    result = str(byte_string[:-1])

    if isinstance(result, bytes):
        result = result.decode('utf-8')

    return str(ipaddress.ip_address(result)) 
開發者ID:yahoo,項目名稱:panoptes,代碼行數:24,代碼來源:helpers.py

示例15: transform_ip_octstr

# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_address [as 別名]
def transform_ip_octstr(ip_octstr):
    """
    Converts octet strings containing IPv4 or IPv6 addresses into a human readable format.
    Args:
        ip_octstr (str): The octet string returned via SNMP
    Returns:
        str: human readable IPv4 or IPv6 IP address:
            2001:dea:0:10::82, 1.2.3.4
    """
    if isinstance(ip_octstr, bytes) and not is_python_2():
        byte_arr = [u'{:02x}'.format(_) for _ in ip_octstr]
    else:
        byte_arr = ['%0.2x' % ord(_) for _ in ip_octstr]
    if len(byte_arr) == 4:
        return '.'.join([str(int(x, 16)) for x in byte_arr])
    else:
        byte_string = ""
        for p, i in enumerate(byte_arr):
            if p % 2 != 0:
                byte_string += '{}{}:'.format(byte_arr[p - 1].lstrip('0'), byte_arr[p])
        # ipaddress formats the string nicely -- collapses blocks of zero
        return str(ipaddress.ip_address(byte_string[:-1].encode('ascii').decode('ascii'))) 
開發者ID:yahoo,項目名稱:panoptes,代碼行數:24,代碼來源:plugin_enrichment_bgp_session_metrics.py


注:本文中的ipaddress.ip_address方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。