Python ipaddress.IPv6Address() Examples

The following are 30 code examples of ipaddress.IPv6Address(). 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: general_name.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #2
Source File: artifacts.py    From ThreatIngestor with GNU General Public License v2.0 6 votes vote down vote up
def is_ipv6(self):
        """Boolean: URL network location is an IPv6 address, not a domain?"""
        # fix urlparse exception
        parsed = urlparse(iocextract.refang_url(self.artifact))

        # Handle RFC 2732 IPv6 URLs with and without port, as well as non-RFC IPv6 URLs
        if ']:' in parsed.netloc:
            ipv6 = ':'.join(parsed.netloc.split(':')[:-1])
        else:
            ipv6 = parsed.netloc

        try:
            ipaddress.IPv6Address(ipv6.replace('[', '').replace(']', ''))
        except ValueError:
            return False

        return True 
Example #3
Source File: socketutil.py    From Pyro5 with MIT License 6 votes vote down vote up
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
    """Bind the socket to a free port and return the port number.
    This code is based on the code in the stdlib's test.test_support module."""
    if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            with contextlib.suppress(socket.error):
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    if not isinstance(host, str):
        host = str(host)
    if sock.family == socket.AF_INET:
        if host == 'localhost':
            sock.bind(('127.0.0.1', 0))
        else:
            sock.bind((host, 0))
    elif sock.family == socket.AF_INET6:
        if host == 'localhost':
            sock.bind(('::1', 0, 0, 0))
        else:
            sock.bind((host, 0, 0, 0))
    else:
        raise CommunicationError("unsupported socket family: " + str(sock.family))
    return sock.getsockname()[1] 
Example #4
Source File: test_pyopenssl.py    From service-identity with MIT License 6 votes vote down vote up
def test_ip(self):
        """
        Returns IP patterns.
        """
        rv = extract_ids(CERT_EVERYTHING)

        assert [
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"*.wildcard.service.identity.invalid"),
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"single.service.identity.invalid"),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"1.1.1.1")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"::1")),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"2.2.2.2")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"2a00:1c38::53")),
        ] == rv 
Example #5
Source File: next_hop.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def __lt__(self, other):
        # String is not comparable with None
        if (self.interface is None) and (other.interface is not None):
            return True
        if (self.interface is not None) and (other.interface is None):
            return False
        if self.interface < other.interface:
            return True
        if self.interface > other.interface:
            return False
        # Address is not comparable with None
        if (self.address is None) and (other.address is not None):
            return True
        if (self.address is not None) and (other.address is None):
            return False
        # Address of different address families are not comparable
        if (isinstance(self.address, ipaddress.IPv4Address) and
                isinstance(other.address, ipaddress.IPv6Address)):
            return True
        if (isinstance(self.address, ipaddress.IPv6Address) and
                isinstance(other.address, ipaddress.IPv4Address)):
            return False
        return self.address < other.address 
Example #6
Source File: test_next_hop.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def test_next_hop_ordering():
    nhop1 = next_hop.NextHop(None, None)
    nhop2 = next_hop.NextHop("if1", None)
    nhop3 = next_hop.NextHop("if1", ipaddress.IPv4Address("1.1.1.1"))
    nhop4 = next_hop.NextHop("if1", ipaddress.IPv4Address("2.2.2.2"))
    nhop5 = next_hop.NextHop("if2", ipaddress.IPv4Address("1.1.1.1"))
    nhop6 = next_hop.NextHop("if2", ipaddress.IPv6Address("1111:1111::"))
    assert nhop1 < nhop2
    assert nhop2 < nhop3
    assert nhop3 < nhop4
    assert nhop4 < nhop5
    assert nhop5 < nhop6
    # pylint:disable=unneeded-not
    assert not nhop2 < nhop1
    assert not nhop3 < nhop2
    assert not nhop4 < nhop3
    assert not nhop5 < nhop4
    assert not nhop6 < nhop5 
Example #7
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 #8
Source File: test_cryptography.py    From service-identity with MIT License 6 votes vote down vote up
def test_ip(self):
        """
        Returns IP patterns.
        """
        rv = extract_ids(CERT_EVERYTHING)

        assert [
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"*.wildcard.service.identity.invalid"),
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"single.service.identity.invalid"),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"1.1.1.1")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"::1")),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"2.2.2.2")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"2a00:1c38::53")),
        ] == rv 
Example #9
Source File: unconfigconfig.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def unconfigure_route_ref(self, conf_obj, path, **kwargs):

        paths = self._path_population([path], kwargs['device'])
        # find position that neighbor (ip) sit
        # replace ip string to IPv4Address object
        for path in paths:
            ipv4_index_list = [path.index(val) for val in path if '.' in str(val)]
            ipv6_index_list = [path.index(val) for val in path if ':' in str(val)]

            for index in ipv4_index_list:
                path[index] = IPv4Address(path[index])
            for index in ipv6_index_list:
                path[index] = IPv6Address(path[index])

        config = '\n'.join([str(conf_path) for conf_path in paths])
        log.info('With following configuration:\n{c}'
                 .format(c=config))

        Configure.conf_configure(device=kwargs['device'],
                                 conf=conf_obj,
                                 conf_structure=paths,
                                 unconfig=True) 
Example #10
Source File: unconfigconfig.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def unconfigure_route_ref(self, conf_obj, path, **kwargs):

        paths = self._path_population([path], kwargs['device'])
        # find position that neighbor (ip) sit
        # replace ip string to IPv4Address object
        for path in paths:
            ipv4_index_list = [path.index(val) for val in path if '.' in str(val)]
            ipv6_index_list = [path.index(val) for val in path if ':' in str(val)]

            for index in ipv4_index_list:
                path[index] = IPv4Address(path[index])
            for index in ipv6_index_list:
                path[index] = IPv6Address(path[index])

        config = '\n'.join([str(conf_path) for conf_path in paths])
        log.info('With following configuration:\n{c}'
                 .format(c=config))

        Configure.conf_configure(device=kwargs['device'],
                                 conf=conf_obj,
                                 conf_structure=paths,
                                 unconfig=True) 
Example #11
Source File: __init__.py    From py-mmdb-encoder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def insert_network(self, prefix, data_offset, strict = True):
        self.entries_count += 1
        ipnet = ipaddress.ip_network(prefix, strict=False)

        if ipnet.version == 6 and self.ip_version != 6:
            raise Exception('Encoder: insert_network: cannot add IPv6 address in IPv4 table')

        if ipnet.version == 4 and self.ip_version == 6:
            base4in6 = ipaddress.IPv6Address(u'::ffff:0:0')
            v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address)+int(base4in6))

            # Maxmind DBs skips the first 96 bits (do not include the 0xffff)
            if self.compat:
                v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address))

            v4in6addr_plen = ipnet.prefixlen + 96
            ipnet = ipaddress.IPv6Network(u'{}/{}'.format(str(v4in6addr), v4in6addr_plen), strict=False)

        #print(ipnet)
        self.add_to_trie(ipnet, data_offset, strict=strict) 
Example #12
Source File: general_name.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #13
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #14
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def testTeredo(self):
        # stolen from wikipedia
        server = ipaddress.IPv4Address('65.54.227.120')
        client = ipaddress.IPv4Address('192.0.2.45')
        teredo_addr = '2001:0000:4136:e378:8000:63bf:3fff:fdd2'
        self.assertEqual((server, client),
                         ipaddress.ip_address(teredo_addr).teredo)
        bad_addr = '2000::4136:e378:8000:63bf:3fff:fdd2'
        self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
        bad_addr = '2001:0001:4136:e378:8000:63bf:3fff:fdd2'
        self.assertFalse(ipaddress.ip_address(bad_addr).teredo)

        # i77
        teredo_addr = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
        self.assertEqual((ipaddress.IPv4Address('94.245.121.253'),
                          ipaddress.IPv4Address('95.26.244.94')),
                         teredo_addr.teredo) 
Example #15
Source File: blockcheck.py    From blockcheck with MIT License 6 votes vote down vote up
def check_ipv6_availability():
    print("Проверка работоспособности IPv6", end='')
    v6addr = _get_a_record("ipv6.icanhazip.com", "AAAA")
    if (v6addr):
        v6 = _get_url("http://ipv6.icanhazip.com/", ip=v6addr[0])
        if len(v6[1]):
            v6src = v6[1].strip()
            if force_ipv6 or (not ipaddress.IPv6Address(v6src).teredo 
                                and not ipaddress.IPv6Address(v6src).sixtofour):
                print(": IPv6 доступен!")
                return v6src
            else:
                print (": обнаружен туннель Teredo или 6to4, игнорируем.")
                return False
    print(": IPv6 недоступен.")
    return False 
Example #16
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 #17
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 #18
Source File: client.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None, timeout=None, source_address=None,
                 *, context=None, check_hostname=None, interface_name=None):

        if interface_name is not None:
            if '%' not in host:
                if isinstance(ipaddress.ip_address(host), ipaddress.IPv6Address):
                    host = host + '%' + interface_name

        if timeout is None:
            timeout = socket.getdefaulttimeout()

        super(HTTPSConnectionAWDL, self).__init__(host=host, port=port, key_file=key_file, cert_file=cert_file,
                                                  timeout=timeout, source_address=source_address, context=context,
                                                  check_hostname=check_hostname)

        self.interface_name = interface_name
        self._create_connection = self.create_connection_awdl 
Example #19
Source File: util.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def get_ip_for_interface(interface_name, ipv6=False):
        """
        Get the ip address in IPv4 or IPv6 for a specific network interface

        :param str interace_name: declares the network interface name for which the ip should be accessed
        :param bool ipv6: Boolean indicating if the ipv6 address should be rertrieved
        :return: (str ipaddress, byte ipaddress_bytes) returns a tuple with the ip address as a string and in bytes
        """
        addresses = netifaces.ifaddresses(interface_name)

        if netifaces.AF_INET6 in addresses and ipv6:
            # Use the normal ipv6 address
            addr = addresses[netifaces.AF_INET6][0]['addr'].split('%')[0]
            bytes_addr = ipaddress.IPv6Address(addr).packed
        elif netifaces.AF_INET in addresses and not ipv6:
            addr = addresses[netifaces.AF_INET][0]['addr']
            bytes_addr = socket.inet_aton(addr)
        else:
            addr = None
            bytes_addr = None

        return addr, bytes_addr 
Example #20
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #21
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #22
Source File: general_name.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #23
Source File: LLD.py    From Zabbix-Template-Juniper-MX-BGP4-ipv4-ipv6 with GNU General Public License v3.0 5 votes vote down vote up
def convert_ip(ip_raw):
    ip_raw = ip_raw.replace(' ', '')
    if len(ip_raw) == 8:
        return str(ipaddress.IPv4Address(int(ip_raw, 16)))
    elif len(ip_raw) == 32:
        return str(ipaddress.IPv6Address(int(ip_raw, 16)))
    else:
        return False 
Example #24
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_address_split_v6_leading_colon(self):
        def assertBadSplit(addr):
            msg = "Leading ':' only permitted as part of '::' in %r"
            with self.assertAddressError(msg, addr):
                ipaddress.IPv6Address(addr)

        assertBadSplit(":2001:db8::1")
        assertBadSplit(":1:2:3:4:5:6:7")
        assertBadSplit(":1:2:3:4:5:6:")
        assertBadSplit(":6:5:4:3:2:1::") 
Example #25
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_address_split_v6_too_many_parts_with_double_colon(self):
        def assertBadSplit(addr):
            msg = "Expected at most 7 other parts with '::' in %r"
            with self.assertAddressError(msg, addr):
                ipaddress.IPv6Address(addr)

        assertBadSplit("1:2:3:4::5:6:7:8") 
Example #26
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_address_split_v6_too_many_parts(self):
        def assertBadSplit(addr):
            msg = "Exactly 8 parts expected without '::' in %r"
            with self.assertAddressError(msg, addr):
                ipaddress.IPv6Address(addr)

        assertBadSplit("3ffe:0:0:0:0:0:0:0:1")
        assertBadSplit("9:8:7:6:5:4:3:2:1")
        assertBadSplit("7:6:5:4:3:2:1")
        # A trailing IPv4 address is two parts
        assertBadSplit("9:8:7:6:5:4:3:42.42.42.42")
        assertBadSplit("7:6:5:4:3:42.42.42.42") 
Example #27
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_address_split_v6_too_many_colons(self):
        def assertBadSplit(addr):
            msg = "At most 8 colons permitted in %r"
            with self.assertAddressError(msg, addr):
                ipaddress.IPv6Address(addr)

        assertBadSplit("9:8:7:6:5:4:3::2:1")
        assertBadSplit("10:9:8:7:6:5:4:3:2:1")
        assertBadSplit("::8:7:6:5:4:3:2:1")
        assertBadSplit("8:7:6:5:4:3:2:1::")
        # A trailing IPv4 address is two parts
        assertBadSplit("10:9:8:7:6:5:4:3:42.42.42.42") 
Example #28
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_address_split_v6_not_enough_parts(self):
        def assertBadSplit(addr):
            msg = "At least 3 parts expected in %r"
            with self.assertAddressError(msg, addr):
                ipaddress.IPv6Address(addr)

        assertBadSplit(":")
        assertBadSplit(":1")
        assertBadSplit("FEDC:9878") 
Example #29
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_network_passed_as_address(self):
        addr = "::1/24"
        with self.assertAddressError("Unexpected '/' in %r", addr):
            ipaddress.IPv6Address(addr) 
Example #30
Source File: neighbor.py    From genielibs with Apache License 2.0 5 votes vote down vote up
def __new__(cls, *args, **kwargs):

        factory_cls = cls
        if cls is IPNeighbor:
            if not kwargs and len(args) == 1 \
                    and isinstance(args[0], IPNeighbor):
                # Copy constructor
                factory_cls = type(args[0])
            else:
                if not kwargs and len(args) == 1:
                    ip = args[0]
                else:
                    try:
                        ip = kwargs['ip']
                    except KeyError:
                        raise TypeError('\'ip\' argument missing')
                if isinstance(ip, (ipaddress.IPv4Interface,
                                   ipaddress.IPv6Interface)):
                    ip = ip.ip
                elif isinstance(ip, (ipaddress.IPv4Address,
                                     ipaddress.IPv6Address)):
                    pass
                else:
                    ip = ipaddress.ip_address(ip)
                if isinstance(ip, ipaddress.IPv4Address):
                    factory_cls = IPv4Neighbor
                elif isinstance(ip, ipaddress.IPv6Address):
                    factory_cls = IPv6Neighbor
                else:
                    raise ValueError(ip)

        if factory_cls is not cls:
            self = factory_cls.__new__(factory_cls, *args, **kwargs)
        elif super().__new__ is object.__new__:
            self = super().__new__(factory_cls)
        else:
            self = super().__new__(factory_cls, *args, **kwargs)
        return self