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


Python ipaddress.AddressValueError方法代码示例

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


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

示例1: scan_network

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def scan_network(self):
        """
        Scan all the hosts specified in the internal hosts list :attr:`self.hosts`.

        :return: A list of :class:`aztarna.sros.helpers.SROSHost` containing all the found hosts.
        """
        try:
            results = []
            for port in self.ports:
                for host_address in self.host_list:
                    results.append(self.scan_host(host_address, port))
            for result in await asyncio.gather(*results):
                if result:
                    self.hosts.append(result)

        except AddressValueError:
            print('Invalid network entered')
        except Exception as e:
            print(e) 
开发者ID:aliasrobotics,项目名称:aztarna,代码行数:21,代码来源:scanner.py

示例2: ip_address_increment

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def ip_address_increment(self,
                             ip_address: str = '192.168.1.1',
                             exit_on_failure: bool = False,
                             exit_code: int = 33,
                             quiet: bool = False) -> Union[None, str]:
        """
        Increment IPv4 address
        :param ip_address: IPv4 address string (example: '192.168.1.1')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 33)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: IPv4 address string (example: '192.168.1.2')
        """
        try:
            return str(IPv4Address(ip_address) + 1)
        except AddressValueError:
            if quiet:
                self.print_error('Bad IPv4 address: ', str(ip_address))
            if exit_on_failure:
                exit(exit_code)
            return None 
开发者ID:raw-packet,项目名称:raw-packet,代码行数:23,代码来源:base.py

示例3: ip_address_decrement

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def ip_address_decrement(self,
                             ip_address: str = '192.168.1.2',
                             exit_on_failure: bool = False,
                             exit_code: int = 34,
                             quiet: bool = False) -> Union[None, str]:
        """
        Decrement IPv4 address
        :param ip_address: IPv4 address string (example: '192.168.1.2')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 33)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: IPv4 address string (example: '192.168.1.1')
        """
        try:
            return str(IPv4Address(ip_address) - 1)
        except AddressValueError:
            if quiet:
                self.print_error('Bad IPv4 address: ', str(ip_address))
            if exit_on_failure:
                exit(exit_code)
            return None 
开发者ID:raw-packet,项目名称:raw-packet,代码行数:23,代码来源:base.py

示例4: is_ipv4

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def is_ipv4(string):
        """
        Checks if a string is a valid ip-address (v4)

        :param string: String to check
        :type string: str

        :return: True if an ip, false otherwise.
        :rtype: bool
        """

        try:
            ipaddress.IPv4Address(string)
            return True
        except ipaddress.AddressValueError:
            return False 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:18,代码来源:utils.py

示例5: is_ipv6

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def is_ipv6(string):
        """
        Checks if a string is a valid ip-address (v6)

        :param string: String to check
        :type string: str

        :return: True if an ipv6, false otherwise.
        :rtype: bool
        """

        try:
            ipaddress.IPv6Address(string)
            return True
        except ipaddress.AddressValueError:
            return False 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:18,代码来源:utils.py

示例6: _get_ips

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _get_ips(self, msg, max_ips=0):
        msg = msg + " Press enter after each one. When finished, just press enter."
        ips = []
        while 1:
            ip_string = message_and_await_string(msg)
            if not ip_string:
                break
            try:
                ips.append(ipaddress.ip_address(ip_string))
                if max_ips != 0 and len(ips) == max_ips:
                    break
            except (ipaddress.AddressValueError, ValueError) as ex:
                L.warning("{}: invalid IP address. Please re-enter.".format(ex))

        if not ips:
            L.warning('User did not provide any valid IP addresses')
        return ips 
开发者ID:expressvpn,项目名称:expressvpn_leak_testing,代码行数:19,代码来源:vpn_application.py

示例7: get_external_ip

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def get_external_ip(self, ip_getter: str) -> Iterator[Deferred]:
        log.info(
            'Retrieving external IP from {!r} to generate server identifier.'.format(ip_getter))
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(ip_getter) as response:
                    ip = await response.text()
                    ip = IPv4Address(ip.strip())
        except AddressValueError as e:
            log.warn('External IP getter service returned invalid data.\n'
                     'Please check the "ip_getter" setting in your config.')
            return
        except Exception as e:  # pylint: disable=broad-except
            log.warn("Getting external IP failed: {reason}", reason=e)
            return

        self.ip = ip
        self.identifier = make_server_identifier(ip, self.port)
        log.info('Server public ip address: {}:{}'.format(ip, self.port))
        log.info('Public aos identifier: {}'.format(self.identifier)) 
开发者ID:piqueserver,项目名称:piqueserver,代码行数:22,代码来源:server.py

示例8: add_peer_address

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def add_peer_address(self, peer_address):
        if peer_address in self.peer_addresses:
            return True

        try:
            ipaddress.IPv4Address(peer_address[0]).packed
        except ipaddress.AddressValueError:
            # peer_address[0] is probably an IPv6 address
            if self.spv.logging_level <= INFO:
                print("[NETWORK] peer address {} is not valid IPv4".format(peer_address[0]))
            return False

        if self.spv.logging_level <= DEBUG:
            print("[NETWORK] new peer found", peer_address)

        self.peer_addresses[peer_address] = {
            'last_successful_connection_time': 0.0,
            'index': self.peer_index,
        }

        self.update_peer_address(peer_address)

        self.peer_index += 1
        return True 
开发者ID:sarchar,项目名称:pyspv,代码行数:26,代码来源:network.py

示例9: ip_address

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def ip_address(self,
                   container: Container,
                   raise_error: bool = False
                   ) -> Optional[Union[IPv4Address, IPv6Address]]:
        """
        The IP address used by a given container, or None if no IP address has
        been assigned to that container.
        """
         # TODO: refactor!
        api_client = docker.APIClient(base_url='unix://var/run/docker.sock')
        docker_info = api_client.inspect_container(container.id)
        address = docker_info['NetworkSettings']['IPAddress']
        try:
            return IPv4Address(address)
        except ipaddress.AddressValueError:
            try:
                return IPv6Address(address)
            except ipaddress.AddressValueError:
                if raise_error:
                    raise
                return None 
开发者ID:squaresLab,项目名称:BugZoo,代码行数:23,代码来源:container.py

示例10: parse_pp1_header

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def parse_pp1_header(data):
    """Return (src_tuple, dest_tuple, remaining_data)"""
    if len(data) < len(PP1_MAGIC):
        raise PPNoEnoughData()
    if not data.startswith(PP1_MAGIC):
        raise PPException('Not a PROXY PROTOCOL version 1 header.')
    if b'\r\n' not in data:
        if len(data) > 128:
            raise PPException('Not a valid PROXY PROTOCOL header.')
        raise PPNoEnoughData()
    header, remaining_data = data.split(b'\r\n', 1)
    try:
        _, family, src, dest, sport, dport = header.split()
        src = str(ip_address(src.decode()))
        dest = str(ip_address(dest.decode()))
        sport = int(sport)
        dport = int(dport)
    except ValueError:
        raise PPException('Not a valid/supported PROXY PROTOCOL header.')
    except AddressValueError:
        raise PPException('Illegal IP address on PROXY PROTOCOL.')
    return ((src, sport), (dest, dport), remaining_data) 
开发者ID:sorz,项目名称:sstp-server,代码行数:24,代码来源:proxy_protocol.py

示例11: qurl_from_user_input

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def qurl_from_user_input(urlstr: str) -> QUrl:
    """Get a QUrl based on a user input. Additionally handles IPv6 addresses.

    QUrl.fromUserInput handles something like '::1' as a file URL instead of an
    IPv6, so we first try to handle it as a valid IPv6, and if that fails we
    use QUrl.fromUserInput.

    WORKAROUND - https://bugreports.qt.io/browse/QTBUG-41089
    FIXME - Maybe https://codereview.qt-project.org/#/c/93851/ has a better way
            to solve this?
    https://github.com/qutebrowser/qutebrowser/issues/109

    Args:
        urlstr: The URL as string.

    Return:
        The converted QUrl.
    """
    # First we try very liberally to separate something like an IPv6 from the
    # rest (e.g. path info or parameters)
    match = re.fullmatch(r'\[?([0-9a-fA-F:.]+)\]?(.*)', urlstr.strip())
    if match:
        ipstr, rest = match.groups()
    else:
        ipstr = urlstr.strip()
        rest = ''
    # Then we try to parse it as an IPv6, and if we fail use
    # QUrl.fromUserInput.
    try:
        ipaddress.IPv6Address(ipstr)
    except ipaddress.AddressValueError:
        return QUrl.fromUserInput(urlstr)
    else:
        return QUrl('http://[{}]{}'.format(ipstr, rest)) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:36,代码来源:urlutils.py

示例12: _is_ip_network

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _is_ip_network(value):
        try:
            ipaddress.IPv4Network(value)
            return True
        except (ValueError, ipaddress.AddressValueError):
            pass
        return False 
开发者ID:mitre,项目名称:caldera,代码行数:9,代码来源:rule_set.py

示例13: _need_enable_ipv6

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _need_enable_ipv6(self, socket_type):
        # Parse the URL
        parsed_url = urlparse(self._address)

        # Get the hostname portion
        hostname = parsed_url.hostname

        # See if the hostname is actually an interface name.
        # In this case, return False.
        if hostname in netifaces.interfaces():
            return False

        # Next, try to directly parse the hostname to determine if we have a
        # literal IPv6 address.
        try:
            IPv6Address(hostname)
            return True
        except AddressValueError:
            pass

        # Finally, if we are setting up a zmq.DEALER docker (client), see if
        # the hostname resolves to an IPv6 address.
        if socket_type == zmq.DEALER:
            try:
                socket.getaddrinfo(parsed_url.hostname, 0,
                                   socket.AddressFamily.AF_INET6,
                                   socket.SocketKind.SOCK_STREAM)
                return True
            except socket.gaierror:
                pass

        # If none of the previous cases returns true, return false.
        return False 
开发者ID:hyperledger,项目名称:sawtooth-core,代码行数:35,代码来源:interconnect.py

示例14: _neighboring_network

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _neighboring_network(cls, interface, after=True):
        prefix = interface.network.prefixlen
        network = interface.network
        try:
            neighbor = network.broadcast_address + 1 if after else network.network_address - 1
        except ipaddress.AddressValueError:
            return None
        return ipaddress.ip_interface('{}/{}'.format(neighbor, prefix)) 
开发者ID:heyglen,项目名称:network_tech,代码行数:10,代码来源:network.py

示例15: range_expander

# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def range_expander(ip):
    try:
        network = ipaddress.IPv4Network(ip)
    except ipaddress.AddressValueError:
        fatal("Invalid IPv4 CIDR: {!r}".format(ip))

    result = list(network)

    return result 
开发者ID:mschwager,项目名称:fierce,代码行数:11,代码来源:fierce.py


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