Python ipaddress.AddressValueError() Examples

The following are 30 code examples of ipaddress.AddressValueError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipaddress , or try the search function .
Example #1
Source File: network.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: vpn_application.py    From expressvpn_leak_testing with MIT License 6 votes vote down vote up
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 
Example #3
Source File: urlutils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #4
Source File: server.py    From piqueserver with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #5
Source File: network.py    From pyspv with MIT License 6 votes vote down vote up
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 
Example #6
Source File: network.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: utils.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: utils.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
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 
Example #10
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
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 
Example #11
Source File: scanner.py    From aztarna with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #12
Source File: container.py    From BugZoo with MIT License 6 votes vote down vote up
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 
Example #13
Source File: proxy_protocol.py    From sstp-server with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def assertAddressError(self, details, *args):
        """Ensure a clean AddressValueError"""
        return self.assertCleanError(ipaddress.AddressValueError,
                                     details, *args) 
Example #15
Source File: sonar_importer.py    From gateway-workflows with Apache License 2.0 5 votes vote down vote up
def _get_assignable_name(self, node):
        assignalbe_name = ''
        try:
            ipaddress.IPv4Address(node['name'])
        except ipaddress.AddressValueError:
            assignalbe_name = node['name']
        return assignalbe_name 
Example #16
Source File: _common.py    From tcconfig with MIT License 5 votes vote down vote up
def normalize_tc_value(tc_obj):
    import ipaddress

    try:
        tc_obj.sanitize()
    except ipaddress.AddressValueError as e:
        logger.error(IPV6_OPTION_ERROR_MSG_FORMAT.format(e))
        sys.exit(errno.EINVAL)
    except ValueError as e:
        logger.error(msgfy.to_error_message(e))
        sys.exit(errno.EINVAL) 
Example #17
Source File: mist_importer.py    From gateway-workflows with Apache License 2.0 5 votes vote down vote up
def _get_assignable_name(self, client):
        assignalbe_name = ''
        try:
            ipaddress.IPv4Address(client['name'])
        except ipaddress.AddressValueError:
            assignalbe_name = client['name']
        return assignalbe_name 
Example #18
Source File: tcset.py    From tcconfig with MIT License 5 votes vote down vote up
def __check_tc(self, tc):
        try:
            tc.validate()
        except (NetworkInterfaceNotFoundError, ContainerNotFoundError) as e:
            logger.error(e)
            return errno.EINVAL
        except ipaddress.AddressValueError as e:
            logger.error(IPV6_OPTION_ERROR_MSG_FORMAT.format(e))
            return errno.EINVAL
        except hr.ParameterError as e:
            logger.error(msgfy.to_error_message(e))
            return errno.EINVAL

        return 0 
Example #19
Source File: _network.py    From tcconfig with MIT License 5 votes vote down vote up
def sanitize_network(network, ip_version):
    """
    :return: Network string
    :rtype: str
    :raises ValueError: if the network string is invalid.
    """

    import ipaddress

    if typepy.is_null_string(network) or network.lower() == "anywhere":
        return get_anywhere_network(ip_version)

    try:
        if ip_version == 4:
            ipaddress.IPv4Address(network)
            return network + "/32"

        if ip_version == 6:
            return ipaddress.IPv6Address(network).compressed
    except ipaddress.AddressValueError:
        pass

    # validate network str ---

    if ip_version == 4:
        return ipaddress.IPv4Network(str(network)).compressed

    if ip_version == 6:
        return ipaddress.IPv6Network(str(network)).compressed

    raise ValueError("unexpected ip version: {}".format(ip_version)) 
Example #20
Source File: resolver.py    From ProxyBroker with Apache License 2.0 5 votes vote down vote up
def host_is_ip(host):
        """Check a host is IP address."""
        # TODO: add IPv6 support
        try:
            ipaddress.IPv4Address(host)
        except ipaddress.AddressValueError:
            return False
        else:
            return True 
Example #21
Source File: test_IPMetadata.py    From QRL with MIT License 5 votes vote down vote up
def test_invalid_1(self):
        with self.assertRaisesRegexp(AddressValueError, 'Address cannot be empty'):
            IPMetadata.from_full_address('') 
Example #22
Source File: test_IPMetadata.py    From QRL with MIT License 5 votes vote down vote up
def test_invalid_2(self):
        with self.assertRaisesRegexp(AddressValueError, 'Expected 4 octets in \'abc\''):
            IPMetadata.from_full_address('abc') 
Example #23
Source File: util.py    From json-spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_ipv4(obj):
    try:
        import ipaddress
        obj = text_type(obj)
        ipaddress.IPv4Address(obj)
    except ImportError:
        raise ValidationError('IPv4 relies on ipaddress package', obj)
    except (ipaddress.AddressValueError, ipaddress.NetmaskValueError):
        raise ValidationError('{!r} does not appear to '
                              'be an IPv4 address'.format(obj))
    return obj 
Example #24
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testEmbeddedIpv4(self):
        ipv4_string = '192.168.0.1'
        ipv4 = ipaddress.IPv4Interface(ipv4_string)
        v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string)
        self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip))
        v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string)
        self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip)
        self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface,
                          '2001:1.1.1.1:1.1.1.1')

    # Issue 67: IPv6 with embedded IPv4 address not recognized. 
Example #25
Source File: test_ipaddress.py    From android_universal with MIT License 5 votes vote down vote up
def testEmbeddedIpv4(self):
        ipv4_string = '192.168.0.1'
        ipv4 = ipaddress.IPv4Interface(ipv4_string)
        v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string)
        self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip))
        v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string)
        self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip)
        self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface,
                          '2001:1.1.1.1:1.1.1.1')

    # Issue 67: IPv6 with embedded IPv4 address not recognized. 
Example #26
Source File: utils.py    From cloud-custodian with Apache License 2.0 5 votes vote down vote up
def parse_cidr(value):
    """Process cidr ranges."""
    klass = IPv4Network
    if '/' not in value:
        klass = ipaddress.ip_address
    try:
        v = klass(str(value))
    except (ipaddress.AddressValueError, ValueError):
        v = None
    return v 
Example #27
Source File: test_ipaddress.py    From android_universal with MIT License 5 votes vote down vote up
def assertAddressError(self, details, *args):
        """Ensure a clean AddressValueError"""
        return self.assertCleanError(ipaddress.AddressValueError,
                                     details, *args) 
Example #28
Source File: util.py    From json-spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_ipv6(obj):
    try:
        import ipaddress
        obj = text_type(obj)
        ipaddress.IPv6Address(obj)
    except ImportError:
        raise ValidationError('IPv6 relies on ipaddress package', obj)
    except (ipaddress.AddressValueError, ipaddress.NetmaskValueError):
        raise ValidationError('{!r} does not appear to '
                              'be an IPv6 address'.format(obj))
    return obj 
Example #29
Source File: base.py    From raw-packet with MIT License 5 votes vote down vote up
def ip_address_in_network(self,
                              ip_address: str = '192.168.1.1',
                              network: str = '192.168.1.0/24',
                              exit_on_failure: bool = False,
                              exit_code: int = 32,
                              quiet: bool = True) -> bool:
        """
        Check IPv4 address in network
        :param ip_address: IPv4 address string (example: '192.168.1.1')
        :param network: IPv4 network string (example: '192.168.1.0/24')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 32)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: True if IPv4 address in network or False if not
        """
        try:
            assert IPAddress(ip_address) in IPNetwork(network), \
                'IPv4 address: ' + self.error_text(str(ip_address)) + \
                ' not in IPv4 network: ' + self.error_text(str(network))
            return True

        except AddressValueError:
            error_text = 'Bad IPv4 address: ' + self.error_text(str(ip_address))

        except AddrFormatError:
            error_text = 'Bad IPv4 network: ' + self.error_text(str(network)) + \
                         ' or IPv4 address: ' + self.error_text(str(ip_address)) + \
                         ' not in IPv4 network: ' + self.error_text(str(network))

        except AssertionError as Error:
            error_text = Error.args[0]

        if not quiet:
            self.print_error(error_text)
        if exit_on_failure:
            exit(exit_code)
        return False 
Example #30
Source File: rule_set.py    From caldera with Apache License 2.0 5 votes vote down vote up
def _is_ip_network(value):
        try:
            ipaddress.IPv4Network(value)
            return True
        except (ValueError, ipaddress.AddressValueError):
            pass
        return False