Python ipaddress.ip_interface() Examples

The following are 30 code examples of ipaddress.ip_interface(). 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: models.py    From KubeOperator with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        dic = {
            "key": "z" + str(self.id).split("-")[3],
            "name": self.cloud_zone,
            "zone_name": self.name,
            "ip_pool": self.ip_pools()
        }
        dic.update(self.vars)
        ip_start = ip_address(self.vars['ip_start'])
        net_mask = self.vars.get('net_mask', None)
        if net_mask:
            interface = ip_interface("{}/{}".format(str(ip_start), net_mask))
            dic["net_mask"] = interface.network.prefixlen
        else:
            dic["net_mask"] = 24
        return dic 
Example #2
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def testHash(self):
        self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
                         hash(ipaddress.ip_interface('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
                         hash(ipaddress.ip_network('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
                         hash(ipaddress.ip_address('10.1.1.0')))
        # i70
        self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
                         hash(ipaddress.ip_address(
                    int(ipaddress.ip_address('1.2.3.4')._ip))))
        ip1 = ipaddress.ip_address('10.1.1.0')
        ip2 = ipaddress.ip_address('1::')
        dummy = {}
        dummy[self.ipv4_address] = None
        dummy[self.ipv6_address] = None
        dummy[ip1] = None
        dummy[ip2] = None
        self.assertIn(self.ipv4_address, dummy)
        self.assertIn(ip2, dummy) 
Example #3
Source File: xcon.py    From vrnetlab with MIT License 6 votes vote down vote up
def _configure_interface_address(self, interface, address, default_route=None):
        next_hop = None
        net = ipaddress.ip_interface(address)
        if default_route:
            try:
                next_hop = ipaddress.ip_address(default_route)
            except ValueError:
                self.logger.error("next-hop address {} could not be parsed".format(default_route))
                sys.exit(1)

        if default_route and next_hop not in net.network:
            self.logger.error("next-hop address {} not in network {}".format(next_hop, net))
            sys.exit(1)

        subprocess.check_call(["ip", "-{}".format(net.version), "address", "add", str(net.ip) + "/" + str(net.network.prefixlen), "dev", interface])
        if next_hop:
            try:
                subprocess.check_call(["ip", "-{}".format(net.version), "route", "del", "default"])
            except:
                pass
            subprocess.check_call(["ip", "-{}".format(net.version), "route", "add", "default", "dev", interface, "via", str(next_hop)]) 
Example #4
Source File: interfaces.py    From netjsonconfig with GNU General Public License v3.0 6 votes vote down vote up
def __netjson_address(self, address, interface):
        ip = ip_interface(address)
        family = 'ipv{0}'.format(ip.version)
        netjson = OrderedDict(
            (
                ('address', str(ip.ip)),
                ('mask', ip.network.prefixlen),
                ('proto', 'static'),
                ('family', family),
            )
        )
        uci_gateway_key = 'gateway' if family == 'ipv4' else 'ip6gw'
        gateway = interface.get(uci_gateway_key, None)
        if gateway and ip_address(gateway) in ip.network:
            netjson['gateway'] = gateway
            del interface[uci_gateway_key]
        return netjson 
Example #5
Source File: routes.py    From netjsonconfig with GNU General Public License v3.0 6 votes vote down vote up
def __intermediate_route(self, route, index):
        network = ip_interface(route.pop('destination'))
        target = network.ip if network.version == 4 else network.network
        route.update(
            {
                '.type': 'route{0}'.format('6' if network.version == 6 else ''),
                '.name': route.pop('name', None) or self.__get_auto_name(index),
                'interface': route.pop('device'),
                'target': str(target),
                'gateway': route.pop('next'),
                'metric': route.pop('cost'),
            }
        )
        if network.version == 4:
            route['netmask'] = str(network.netmask)
        return self.sorted_dict(route) 
Example #6
Source File: routes.py    From netjsonconfig with GNU General Public License v3.0 6 votes vote down vote up
def __netjson_route(self, route, i):
        _name = route.pop('.name')
        if _name != self.__get_auto_name(i):
            route['name'] = _name
        network = route.pop('target')
        if 'netmask' in route:
            network = '{0}/{1}'.format(network, route.pop('netmask'))
        route.update(
            {
                "device": route.pop('interface'),
                "destination": str(ip_interface(network)),
                "next": route.pop('gateway'),
                "cost": route.pop(
                    'metric', self._schema['properties']['cost']['default']
                ),
            }
        )
        del route['.type']
        return self.type_cast(route) 
Example #7
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def testHash(self):
        self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
                         hash(ipaddress.ip_interface('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
                         hash(ipaddress.ip_network('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
                         hash(ipaddress.ip_address('10.1.1.0')))
        # i70
        self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
                         hash(ipaddress.ip_address(
                    int(ipaddress.ip_address('1.2.3.4')._ip))))
        ip1 = ipaddress.ip_address('10.1.1.0')
        ip2 = ipaddress.ip_address('1::')
        dummy = {}
        dummy[self.ipv4_address] = None
        dummy[self.ipv6_address] = None
        dummy[ip1] = None
        dummy[ip2] = None
        self.assertIn(self.ipv4_address, dummy)
        self.assertIn(ip2, dummy) 
Example #8
Source File: network.py    From network_tech with Apache License 2.0 6 votes vote down vote up
def ptr_lookup(cls, network):
        ip = str(ipaddress.ip_interface(network).ip)
        try:
            primary_hostname, alias_hostnames, other_ips = socket.gethostbyaddr(ip)
        except socket.herror as e:
            logger.debug('DNS Reverse Lookup Error {}'.format(e))
            return Html.div('DNS: n/a')

        content = Html.div(
            'DNS: {}'.format(
                socket.getfqdn(primary_hostname)
            )
        )

        if alias_hostnames:
            content += Html.div('DNS Aliases:')
        for hostname in alias_hostnames:
            fqdn_hostname = socket.getfqdn(hostname)
            logger.debug('Alias {} FQDN {}'.format(hostname, fqdn_hostname))
            content += Html.div(fqdn_hostname)
        return content 
Example #9
Source File: link.py    From ipmininet with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, if1: IPIntf, if2: IPIntf,
                 if1address: Union[str, IPv4Interface, IPv6Interface],
                 if2address: Union[str, IPv4Interface, IPv6Interface],
                 bidirectional=True):
        """:param if1: The first interface of the tunnel
        :param if2: The second interface of the tunnel
        :param if1address: The ip_interface address for if1
        :param if2address: The ip_interface address for if2
        :param bidirectional: Whether both end of the tunnel should be
                              established or not. GRE is stateless so there is
                              no handshake per-say, however if one end of the
                              tunnel is not established, the kernel will drop
                              by default the encapsulated packets."""
        self.if1, self.if2 = if1, if2
        self.ip1, self.gre1 = (ip_interface(str(if1address)),
                               self._gre_name(if1))
        self.ip2, self.gre2 = (ip_interface(str(if2address)),
                               self._gre_name(if2))
        self.bidirectional = bidirectional
        self.setup_tunnel() 
Example #10
Source File: models.py    From KubeOperator with Apache License 2.0 6 votes vote down vote up
def ip_pools(self):
        ip_pool = []
        ip_start = ip_address(self.vars['ip_start'])
        ip_end = ip_address(self.vars['ip_end'])

        if self.region.template.name == 'openstack':
            while ip_start <= ip_end:
                ip_pool.append(str(ip_start))
                ip_start += 1
            for ip in self.ip_used:
                if ip in ip_pool:
                    ip_pool.remove(ip)
            return ip_pool

        net_mask = self.vars['net_mask']
        interface = ip_interface("{}/{}".format(str(ip_start), net_mask))
        network = interface.network
        for host in network.hosts():
            if ip_start <= host <= ip_end:
                ip_pool.append(str(host))
        for ip in self.ip_used:
            if ip in ip_pool:
                ip_pool.remove(ip)
        return ip_pool 
Example #11
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def testHash(self):
        self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
                         hash(ipaddress.ip_interface('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
                         hash(ipaddress.ip_network('10.1.1.0/24')))
        self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
                         hash(ipaddress.ip_address('10.1.1.0')))
        # i70
        self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
                         hash(ipaddress.ip_address(
                    int(ipaddress.ip_address('1.2.3.4')._ip))))
        ip1 = ipaddress.ip_address('10.1.1.0')
        ip2 = ipaddress.ip_address('1::')
        dummy = {}
        dummy[self.ipv4_address] = None
        dummy[self.ipv6_address] = None
        dummy[ip1] = None
        dummy[ip2] = None
        self.assertIn(self.ipv4_address, dummy)
        self.assertIn(ip2, dummy) 
Example #12
Source File: filters.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (
            Q(autonomous_system__name__icontains=value)
            | Q(internet_exchange__name__icontains=value)
            | Q(internet_exchange__slug__icontains=value)
            | Q(comments__icontains=value)
        )
        try:
            ip = ipaddress.ip_interface(value.strip())
            qs_filter |= Q(ip_address__host=str(ip))
        except ValueError:
            pass
        try:
            qs_filter |= Q(autonomous_system__asn=int(value.strip()))
        except ValueError:
            pass
        return queryset.filter(qs_filter) 
Example #13
Source File: filters.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(network__name__icontains=value) | Q(
            network__irr_as_set__icontains=value
        )
        try:
            ip = ipaddress.ip_interface(value.strip())
            qs_filter |= Q(network_ixlan__ipaddr6__host=str(ip))
            qs_filter |= Q(network_ixlan__ipaddr4__host=str(ip))
        except ValueError:
            pass
        try:
            qs_filter |= Q(network__asn=int(value.strip()))
            qs_filter |= Q(network__info_prefixes6=int(value.strip()))
            qs_filter |= Q(network__info_prefixes4=int(value.strip()))
        except ValueError:
            pass
        return queryset.filter(qs_filter) 
Example #14
Source File: mininet_test_base.py    From faucet with Apache License 2.0 6 votes vote down vote up
def verify_ipv4_routing_mesh(self):
        """Verify hosts can route to each other via FAUCET."""
        host_pair = self.hosts_name_ordered()[:2]
        first_host, second_host = host_pair
        first_host_routed_ip = ipaddress.ip_interface('10.0.1.1/24')
        second_host_routed_ip = ipaddress.ip_interface('10.0.2.1/24')
        second_host_routed_ip2 = ipaddress.ip_interface('10.0.3.1/24')
        self.verify_ipv4_routing(
            first_host, first_host_routed_ip,
            second_host, second_host_routed_ip)
        self.verify_ipv4_routing(
            first_host, first_host_routed_ip,
            second_host, second_host_routed_ip2)
        self.swap_host_macs(first_host, second_host)
        self.verify_ipv4_routing(
            first_host, first_host_routed_ip,
            second_host, second_host_routed_ip)
        self.verify_ipv4_routing(
            first_host, first_host_routed_ip,
            second_host, second_host_routed_ip2) 
Example #15
Source File: mininet_test_base.py    From faucet with Apache License 2.0 6 votes vote down vote up
def verify_ipv6_routing_mesh(self):
        """Verify IPv6 routing between hosts and multiple subnets."""
        host_pair = self.hosts_name_ordered()[:2]
        first_host, second_host = host_pair
        first_host_ip = ipaddress.ip_interface('fc00::1:1/112')
        second_host_ip = ipaddress.ip_interface('fc00::1:2/112')
        first_host_routed_ip = ipaddress.ip_interface('fc00::10:1/112')
        second_host_routed_ip = ipaddress.ip_interface('fc00::20:1/112')
        second_host_routed_ip2 = ipaddress.ip_interface('fc00::30:1/112')
        self.verify_ipv6_routing_pair(
            first_host, first_host_ip, first_host_routed_ip,
            second_host, second_host_ip, second_host_routed_ip)
        self.verify_ipv6_routing_pair(
            first_host, first_host_ip, first_host_routed_ip,
            second_host, second_host_ip, second_host_routed_ip2)
        self.swap_host_macs(first_host, second_host)
        self.verify_ipv6_routing_pair(
            first_host, first_host_ip, first_host_routed_ip,
            second_host, second_host_ip, second_host_routed_ip)
        self.verify_ipv6_routing_pair(
            first_host, first_host_ip, first_host_routed_ip,
            second_host, second_host_ip, second_host_routed_ip2) 
Example #16
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testCopyConstructor(self):
        addr1 = ipaddress.ip_network('10.1.1.0/24')
        addr2 = ipaddress.ip_network(addr1)
        addr3 = ipaddress.ip_interface('2001:658:22a:cafe:200::1/64')
        addr4 = ipaddress.ip_interface(addr3)
        addr5 = ipaddress.IPv4Address('1.1.1.1')
        addr6 = ipaddress.IPv6Address('2001:658:22a:cafe:200::1')

        self.assertEqual(addr1, addr2)
        self.assertEqual(addr3, addr4)
        self.assertEqual(addr5, ipaddress.IPv4Address(addr5))
        self.assertEqual(addr6, ipaddress.IPv6Address(addr6)) 
Example #17
Source File: ipnet.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def interface(self, x, y):
        """Return the ip_interface for node x facing node y"""
        return ip_interface(self._interface(x, y)['ip']) 
Example #18
Source File: lsa.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def prefix(self):
        return ip_interface('%s/%s' % (self.address, self.mask)).with_prefixlen 
Example #19
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 testCopyConstructor(self):
        addr1 = ipaddress.ip_network('10.1.1.0/24')
        addr2 = ipaddress.ip_network(addr1)
        addr3 = ipaddress.ip_interface('2001:658:22a:cafe:200::1/64')
        addr4 = ipaddress.ip_interface(addr3)
        addr5 = ipaddress.IPv4Address('1.1.1.1')
        addr6 = ipaddress.IPv6Address('2001:658:22a:cafe:200::1')

        self.assertEqual(addr1, addr2)
        self.assertEqual(addr3, addr4)
        self.assertEqual(addr5, ipaddress.IPv4Address(addr5))
        self.assertEqual(addr6, ipaddress.IPv6Address(addr6)) 
Example #20
Source File: iprouter.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def build_ospf(self, router):
        cfg = super(MininetRouterConfig, self).build_ospf(router)
        networks = []
        for itf in router.ospf_interfaces():
            c = itf.params.get('cost', FIBBING_MIN_COST)
            if c > 0:
                cfg.interfaces.append(
                    ConfigDict(name=itf.name,
                               description=str(itf.link),
                               ospf=ConfigDict(
                                    cost=c,
                                    priority=10,
                                    dead_int=router.dead_interval,
                                    hello_int=router.hello_interval)))
                area = itf.params.get('area', FIBBING_DEFAULT_AREA)
                networks.append((ip_interface('%s/%s' %
                                              (itf.ip, itf.prefixLen))
                                .network, area))
                # TODO figure out the private config knob so that the private
                # addresses dont create redundant OSPF session over the same
                # interface ...
                try:
                    networks.extend((ip_interface(net).network, area)
                                    for net in itf.params[PRIVATE_IP_KEY])
                except KeyError:
                    pass  # No private ip on that interface
            else:
                cfg.passive_interfaces.append(itf)
        for net, area in networks:
            cfg.networks.append(ConfigDict(domain=net.with_prefixlen,
                                           area=area))
        return cfg 
Example #21
Source File: awl.py    From OrangeAssassin with Apache License 2.0 5 votes vote down vote up
def ip_to_awl_key(self, ip):
        if ip.version == 4:
            mask = self["auto_whitelist_ipv4_mask_len"]
        else:
            mask = self["auto_whitelist_ipv6_mask_len"]

        interface = ipaddress.ip_interface("%s/%s" % (ip, mask))
        network = interface.network.network_address
        return IPV4SUFFIXRE.sub("", str(network)) 
Example #22
Source File: controllers.py    From kuryr-libnetwork with Apache License 2.0 5 votes vote down vote up
def _get_fixed_ips_by_interface_cidr(subnets, interface_cidrv4,
                                     interface_cidrv6, fixed_ips):
    for subnet in subnets:
        fixed_ip = [('subnet_id=%s' % subnet['id'])]
        if interface_cidrv4 or interface_cidrv6:
            if subnet['ip_version'] == 4 and interface_cidrv4:
                iface = ipaddress.ip_interface(str(interface_cidrv4))
            elif subnet['ip_version'] == 6 and interface_cidrv6:
                iface = ipaddress.ip_interface(str(interface_cidrv6))
            if str(subnet['cidr']) != str(iface.network):
                continue
            fixed_ip.append('ip_address=%s' % iface.ip)
        fixed_ips.extend(fixed_ip) 
Example #23
Source File: controllers.py    From kuryr-libnetwork with Apache License 2.0 5 votes vote down vote up
def _process_interface_address(port_dict, subnets_dict_by_id,
                               response_interface):
    subnet_id = port_dict['subnet_id']
    subnet = subnets_dict_by_id[subnet_id]
    iface = ipaddress.ip_interface(str(subnet['cidr']))
    address_key = 'Address' if iface.version == 4 else 'AddressIPv6'
    response_interface[address_key] = str(iface) 
Example #24
Source File: controllers.py    From kuryr-libnetwork with Apache License 2.0 5 votes vote down vote up
def _get_subnets_by_interface_cidr(neutron_network_id,
                                   interface_cidr):
    iface = ipaddress.ip_interface(str(interface_cidr))
    subnets = _get_subnets_by_attrs(
        network_id=neutron_network_id, cidr=str(iface.network))
    if len(subnets) > 2:
        raise exceptions.DuplicatedResourceException(
            "Multiple Neutron subnets exist for the network_id={0}"
            "and cidr={1}"
            .format(neutron_network_id, iface.network))
    return subnets 
Example #25
Source File: test_macos_webrtc_ice_force_enable_ipv6.py    From expressvpn_leak_testing with MIT License 5 votes vote down vote up
def test(self):
        L.describe('Get the public IP addresses before VPN connect')
        public_ips_before_connect = self.localhost['ip_tool'].all_public_ip_addresses()

        # Sanity check: We should always have at least one IP address!
        self.assertNotEmpty(public_ips_before_connect, "Couldn't get public IP addresses")
        L.info("Public IP addresses before VPN connect are {}".format(public_ips_before_connect))

        L.describe('Open and connect the VPN application')
        self.localhost['vpn_application'].open_and_connect()

        L.describe('Forcibly enable IPv6 on all active network services')
        self.enable_ipv6_on_all_active_services()

        L.describe('Find IPs reported by WebRTC')
        webdriver = self.localhost['webdriver'].driver(self.parameters['browser'])
        webrtc_ice_checker = WebRTCICEHelper(
            self.localhost,
            webdriver,
            self.parameters['ask_perms'],
            self.parameters['host_remotely'])

        webrtc_ips = webrtc_ice_checker.webrtc_ips()

        L.info("Found the following WebRTC IPs: {}".format(webrtc_ips))

        L.describe(
            'Check IPv4 addresses reported by WebRTC are all unknown and IPv6 '
            'addresses are in a different subnet')

        ipv6_subnets = [ipaddress.ip_interface((ip, 64)).network
                        for ip in public_ips_before_connect if ip.version == 6]
        for ip in webrtc_ips:
            self.assertIsNotIn(
                ip, public_ips_before_connect,
                "Found public IP {} in ICE IPs".format(ip))
            if ip.version == 6:
                for subnet in ipv6_subnets:
                    self.assertFalse(
                        ip in subnet,
                        "New IPv6 address {} is in {}".format(ip, subnet)) 
Example #26
Source File: helpers.py    From recon-pipeline with MIT License 5 votes vote down vote up
def is_ip_address(ipaddr):
    """ Simple helper to determine if given string is an ip address or subnet """
    try:
        ipaddress.ip_interface(ipaddr)
        return True
    except ValueError:
        return False 
Example #27
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testInterfaceComparison(self):
        self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
                        ipaddress.ip_interface('1.1.1.1'))
        self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
                        ipaddress.ip_interface('1.1.1.2'))
        self.assertTrue(ipaddress.ip_interface('::1') <=
                        ipaddress.ip_interface('::1'))
        self.assertTrue(ipaddress.ip_interface('::1') <=
                        ipaddress.ip_interface('::2')) 
Example #28
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testIpFromPacked(self):
        address = ipaddress.ip_address
        self.assertEqual(self.ipv4_interface._ip,
                         ipaddress.ip_interface(b'\x01\x02\x03\x04')._ip)
        self.assertEqual(address('255.254.253.252'),
                         address(b'\xff\xfe\xfd\xfc'))
        self.assertEqual(self.ipv6_interface.ip,
                         ipaddress.ip_interface(
                    b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
                    b'\x02\x00\x00\x00\x00\x00\x00\x01').ip)
        self.assertEqual(address('ffff:2:3:4:ffff::'),
                         address(b'\xff\xff\x00\x02\x00\x03\x00\x04' +
                            b'\xff\xff' + b'\x00' * 6))
        self.assertEqual(address('::'),
                         address(b'\x00' * 16)) 
Example #29
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_ip_interface(self):
        self.assertFactoryError(ipaddress.ip_interface, "interface") 
Example #30
Source File: openr.py    From ipmininet with GNU General Public License v2.0 5 votes vote down vote up
def _build_networks(interfaces):
        """Return the list of OpenR networks to advertize from the list of
        active OpenR interfaces"""
        # Check that we have at least one IPv4 network on that interface ...
        return [OpenrNetwork(domain=ip_interface('%s/%s' % (i.ip, i.prefixLen)))
                for i in interfaces if i.ip]