Python ipaddress.IPv4Interface() Examples

The following are 30 code examples of ipaddress.IPv4Interface(). 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: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def testEqual(self):
        self.assertTrue(self.ipv4_interface ==
                        ipaddress.IPv4Interface('1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv6Interface('::1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface == '')
        self.assertFalse(self.ipv4_interface == [])
        self.assertFalse(self.ipv4_interface == 2)

        self.assertTrue(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
        self.assertFalse(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
        self.assertFalse(self.ipv6_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv6_interface == '')
        self.assertFalse(self.ipv6_interface == [])
        self.assertFalse(self.ipv6_interface == 2) 
Example #2
Source File: test_ipaddress.py    From android_universal with MIT License 6 votes vote down vote up
def testEqual(self):
        self.assertTrue(self.ipv4_interface ==
                        ipaddress.IPv4Interface('1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv6Interface('::1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface == '')
        self.assertFalse(self.ipv4_interface == [])
        self.assertFalse(self.ipv4_interface == 2)

        self.assertTrue(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
        self.assertFalse(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
        self.assertFalse(self.ipv6_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv6_interface == '')
        self.assertFalse(self.ipv6_interface == [])
        self.assertFalse(self.ipv6_interface == 2) 
Example #3
Source File: ip.py    From satellite with GNU General Public License v3.0 6 votes vote down vote up
def _set_static_iface_ip(ifname, ipv4_if, is_root):
    """Set static IP address for target network interface

    Args:
        ifname  : Network device name
        ipv4_if : IPv4Interface object with the target interface address
        is_root : (bool) whether running as root

    """
    isinstance(ipv4_if, IPv4Interface)
    addr                = str(ipv4_if.ip)
    addr_with_prefix    = ipv4_if.with_prefixlen
    netmask             = str(ipv4_if.netmask)

    if (which("netplan") is not None):
        _add_to_netplan(ifname, addr_with_prefix, is_root)
    elif (os.path.exists("/etc/network/interfaces.d/")):
        _add_to_interfaces_d(ifname, addr, netmask, is_root)
    elif (os.path.exists("/etc/sysconfig/network-scripts")):
        _add_to_sysconfig_net_scripts(ifname, addr, netmask, is_root)
    else:
        raise ValueError("Could not set a static IP address on interface "
                         "{}".format(ifname)) 
Example #4
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def testIpFromInt(self):
        self.assertEqual(self.ipv4_interface._ip,
                         ipaddress.IPv4Interface(16909060)._ip)

        ipv4 = ipaddress.ip_network('1.2.3.4')
        ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
        self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
        self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))

        v6_int = 42540616829182469433547762482097946625
        self.assertEqual(self.ipv6_interface._ip,
                         ipaddress.IPv6Interface(v6_int)._ip)

        self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
                         4)
        self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
                         6) 
Example #5
Source File: ip.py    From satellite with GNU General Public License v3.0 6 votes vote down vote up
def _set_ip(net_if, ip_addr, verbose):
    """Set the IP of the DVB network interface

    Args:
        net_if    : DVB network interface name
        ip_addr   : Target IP address for the DVB interface slash subnet mask
        verbose   : Controls verbosity

    """
    is_root       = (os.geteuid() == 0)
    inet_if       = IPv4Interface(ip_addr)

    # Flush previous IP
    if (not is_root):
        print("Flush any IP address from {}:\n".format(net_if))
    res = util.run_or_print_root_cmd(["ip", "address", "flush", "dev", net_if],
                                     logger)

    # Configure new static IP
    _set_static_iface_ip(net_if, inet_if, is_root) 
Example #6
Source File: test_ipaddress.py    From android_universal with MIT License 6 votes vote down vote up
def testIpFromInt(self):
        self.assertEqual(self.ipv4_interface._ip,
                         ipaddress.IPv4Interface(16909060)._ip)

        ipv4 = ipaddress.ip_network('1.2.3.4')
        ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
        self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
        self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))

        v6_int = 42540616829182469433547762482097946625
        self.assertEqual(self.ipv6_interface._ip,
                         ipaddress.IPv6Interface(v6_int)._ip)

        self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
                         4)
        self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
                         6) 
Example #7
Source File: ip.py    From ttp with MIT License 6 votes vote down vote up
def to_ip(data, *args):
    # for py2 support need to convert data to unicode:
    if _ttp_["python_major_version"] is 2:
        ipaddr_data = unicode(data)
    elif _ttp_["python_major_version"] is 3:
        ipaddr_data = data
    if "ipv4" in args:
        if "/" in ipaddr_data or " " in ipaddr_data:
            return ipaddress.IPv4Interface(ipaddr_data.replace(" ", "/")), None
        else:
            return ipaddress.IPv4Address(ipaddr_data), None
    elif "ipv6" in args:
        if "/" in ipaddr_data:
            return ipaddress.IPv6Interface(ipaddr_data), None
        else:
            return ipaddress.IPv6Address(ipaddr_data), None
    elif "/" in ipaddr_data or " " in ipaddr_data:
        return ipaddress.ip_interface(ipaddr_data.replace(" ", "/")), None
    else:
        return ipaddress.ip_address(ipaddr_data), None 
Example #8
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 #9
Source File: __router.py    From ipmininet with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, name,
                 config: Union[Type[RouterConfig],
                               Tuple[Type[RouterConfig],
                                     Dict]] = BasicRouterConfig,
                 password='zebra',
                 lo_addresses: Sequence[Union[str, IPv4Interface,
                                              IPv6Interface]] = (),
                 *args, **kwargs):
        """:param password: The password for the routing daemons vtysh access
           :param lo_addresses: The list of addresses to set on the loopback
                                interface"""
        super().__init__(name, config=config, *args, **kwargs)
        self.password = password

        # This interface already exists in the node,
        # so no need to move it
        lo = IPIntf('lo', node=self, port=-1, moveIntfFn=lambda x, y: None)
        lo.ip = lo_addresses 
Example #10
Source File: conf.py    From faucet with Apache License 2.0 6 votes vote down vote up
def _str_conf(self, conf_v):
        if isinstance(conf_v, (bool, str, int)):
            return conf_v
        if isinstance(conf_v, (
                ipaddress.IPv4Address, ipaddress.IPv4Interface, ipaddress.IPv4Network,
                ipaddress.IPv6Address, ipaddress.IPv6Interface, ipaddress.IPv6Network)):
            return str(conf_v)
        if isinstance(conf_v, (dict, OrderedDict)):
            return {str(i): self._str_conf(j) for i, j in conf_v.items() if j is not None}
        if isinstance(conf_v, (list, tuple, frozenset)):
            return tuple([self._str_conf(i) for i in conf_v if i is not None])
        if isinstance(conf_v, Conf):
            for i in ('name', '_id'):
                if hasattr(conf_v, i):
                    return getattr(conf_v, i)
        return None 
Example #11
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def testIpFromInt(self):
        self.assertEqual(self.ipv4_interface._ip,
                         ipaddress.IPv4Interface(16909060)._ip)

        ipv4 = ipaddress.ip_network('1.2.3.4')
        ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
        self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
        self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))

        v6_int = 42540616829182469433547762482097946625
        self.assertEqual(self.ipv6_interface._ip,
                         ipaddress.IPv6Interface(v6_int)._ip)

        self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
                         4)
        self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
                         6) 
Example #12
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def testEqual(self):
        self.assertTrue(self.ipv4_interface ==
                        ipaddress.IPv4Interface('1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv6Interface('::1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface == '')
        self.assertFalse(self.ipv4_interface == [])
        self.assertFalse(self.ipv4_interface == 2)

        self.assertTrue(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
        self.assertFalse(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
        self.assertFalse(self.ipv6_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv6_interface == '')
        self.assertFalse(self.ipv6_interface == [])
        self.assertFalse(self.ipv6_interface == 2) 
Example #13
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 testEqual(self):
        self.assertTrue(self.ipv4_interface ==
                        ipaddress.IPv4Interface('1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv4_interface ==
                         ipaddress.IPv6Interface('::1.2.3.4/24'))
        self.assertFalse(self.ipv4_interface == '')
        self.assertFalse(self.ipv4_interface == [])
        self.assertFalse(self.ipv4_interface == 2)

        self.assertTrue(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
        self.assertFalse(self.ipv6_interface ==
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
        self.assertFalse(self.ipv6_interface ==
                         ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertFalse(self.ipv6_interface == '')
        self.assertFalse(self.ipv6_interface == [])
        self.assertFalse(self.ipv6_interface == 2) 
Example #14
Source File: vpn.py    From telepresence with Apache License 2.0 6 votes vote down vote up
def covering_cidr(ips: List[str]) -> str:
    """
    Given list of IPs, return CIDR that covers them all.

    Presumes it's at least a /24.
    """
    def collapse(ns):
        return list(ipaddress.collapse_addresses(ns))

    assert len(ips) > 0
    networks = collapse([
        ipaddress.IPv4Interface(ip + "/24").network for ip in ips
    ])
    # Increase network size until it combines everything:
    while len(networks) > 1:
        networks = collapse([networks[0].supernet()] + networks[1:])
    return networks[0].with_prefixlen


# Script to dump resolved IPs to stdout as JSON list: 
Example #15
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 testIpFromInt(self):
        self.assertEqual(self.ipv4_interface._ip,
                         ipaddress.IPv4Interface(16909060)._ip)

        ipv4 = ipaddress.ip_network('1.2.3.4')
        ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
        self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
        self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))

        v6_int = 42540616829182469433547762482097946625
        self.assertEqual(self.ipv6_interface._ip,
                         ipaddress.IPv6Interface(v6_int)._ip)

        self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
                         4)
        self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
                         6) 
Example #16
Source File: validators.py    From pydantic with MIT License 5 votes vote down vote up
def ip_v4_interface_validator(v: Any) -> IPv4Interface:
    if isinstance(v, IPv4Interface):
        return v

    try:
        return IPv4Interface(v)
    except ValueError:
        raise errors.IPv4InterfaceError() 
Example #17
Source File: ip.py    From ttp with MIT License 5 votes vote down vote up
def cidr_match(data, prefix):
    # try to get value from TTP vars variables
    prefix = _ttp_["parser_object"].vars.get(prefix, prefix)
    # convert data to ipaddress object:
    if isinstance(data, str):
        try:
            ip_obj = to_ip(data)[0]
        except ValueError:
            return data, None
    else:
        ip_obj = data 
    # create ipaddress ipnetwork object out of prefix
    ip_net = to_net(prefix)[0]         
    if isinstance(ip_obj, ipaddress.IPv4Interface) or isinstance(ip_obj, ipaddress.IPv6Interface):
        # if object is ipnetwork, can check it as is:
        check = ip_obj.network.overlaps(ip_net)
    elif isinstance(ip_obj, ipaddress.IPv4Address) or isinstance(ip_obj, ipaddress.IPv6Address):
        # if object is ipaddress, need to convert it itno ipinterface with /32 mask:
        if ip_obj.version is 4:
            # for py2 support need to convert data to unicode:
            if _ttp_["python_major_version"] is 2:
                ipaddr_data = unicode("{}/32".format(str(ip_obj)))
            elif _ttp_["python_major_version"] is 3:
                ipaddr_data = "{}/32".format(str(ip_obj))
            ip_obj = ipaddress.IPv4Interface(ipaddr_data)
        elif ip_obj.version is 6:
            # for py2 support need to convert data to unicode:
            if _ttp_["python_major_version"] is 2:
                ipaddr_data = unicode("{}/128".format(str(ip_obj)))
            elif _ttp_["python_major_version"] is 3:
                ipaddr_data = "{}/128".format(str(ip_obj))
            ip_obj = ipaddress.IPv6Interface(ipaddr_data)
        check = ip_obj.network.overlaps(ip_net)
    else:
        check = None
    return data, check 
Example #18
Source File: validators.py    From pydantic with MIT License 5 votes vote down vote up
def check(self, config: Type['BaseConfig']) -> bool:
        return any(getattr(config, name) not in {None, False} for name in self.config_attr_names)


# order is important here, for example: bool is a subclass of int so has to come first, datetime before date same,
# IPv4Interface before IPv4Address, etc 
Example #19
Source File: test_ipaddress.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
        self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
        self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
        #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
        self.ipv6_address = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1')
        self.ipv6_interface = ipaddress.IPv6Interface(
            '2001:658:22a:cafe:200:0:0:1/64')
        self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64') 
Example #20
Source File: network_config_helper.py    From fluxclient with GNU Affero General Public License v3.0 5 votes vote down vote up
def run():
    from fluxclient.utils.network_config import parse_network_config

    kw = {}
    ret = input("Wifi Mode (0=host,1=client)[1]: ").strip("\n")
    if ret == "0":
        kw["wifi_mode"] = "host"
    else:
        kw["wifi_mode"] = "client"

    kw["ssid"] = input("SSID: ").strip("\n")

    ret = input("Is SSID hidden? (y/n)[n]: ").strip("\n")
    if ret.upper() == "Y":
        kw["scan_ssid"] = "1"

    ret = input("Wifi-Protection (0=None,1=WEP,2=WPA2-PSK)[2]: ").strip("\n")
    if ret == "0":
        kw["security"] = "None"
    elif ret == "1":
        kw["security"] = "WEP"
        kw["wepkey"] = input("Wifi password: ").strip("\n")
    else:
        kw["security"] = "WPA2-PSK"
        kw["psk"] = input("Wifi password: ").strip("\n")

    ret = input("Use DHCP? (0=YES,1=NO)[0]: ").strip("\n")
    if ret == "1":
        kw["method"] = "static"
        ipaddr = IPv4Interface(
            input("IP Address (example: \"192.168.0.1/24\"): ").strip("\n"))
        kw["ipaddr"] = str(ipaddr.ip)
        kw["mask"] = int(ipaddr.with_prefixlen.split("/")[-1])
        gw = IPv4Address(input("Gateway: ").strip("\n"))
        kw["route"] = str(gw)
        kw["ns"] = input("DNS: ").strip("\n")
    else:
        kw["method"] = "dhcp"

    print(">>", kw)
    return parse_network_config(**kw) 
Example #21
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 #22
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 #23
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 testSlash0Constructor(self):
        self.assertEqual(str(ipaddress.IPv4Interface('1.2.3.4/0.0.0.0')),
                          '1.2.3.4/0') 
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 testSlash32Constructor(self):
        self.assertEqual(str(ipaddress.IPv4Interface(
                    '1.2.3.4/255.255.255.255')), '1.2.3.4/32') 
Example #25
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 testNotEqual(self):
        self.assertFalse(self.ipv4_interface !=
                         ipaddress.IPv4Interface('1.2.3.4/24'))
        self.assertTrue(self.ipv4_interface !=
                        ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertTrue(self.ipv4_interface !=
                        ipaddress.IPv6Interface('::1.2.3.4/24'))
        self.assertTrue(self.ipv4_interface != '')
        self.assertTrue(self.ipv4_interface != [])
        self.assertTrue(self.ipv4_interface != 2)

        self.assertTrue(self.ipv4_address !=
                         ipaddress.IPv4Address('1.2.3.5'))
        self.assertTrue(self.ipv4_address != '')
        self.assertTrue(self.ipv4_address != [])
        self.assertTrue(self.ipv4_address != 2)

        self.assertFalse(self.ipv6_interface !=
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
        self.assertTrue(self.ipv6_interface !=
            ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
        self.assertTrue(self.ipv6_interface !=
                        ipaddress.IPv4Interface('1.2.3.4/23'))
        self.assertTrue(self.ipv6_interface != '')
        self.assertTrue(self.ipv6_interface != [])
        self.assertTrue(self.ipv6_interface != 2)

        self.assertTrue(self.ipv6_address !=
                        ipaddress.IPv4Address('1.2.3.4'))
        self.assertTrue(self.ipv6_address != '')
        self.assertTrue(self.ipv6_address != [])
        self.assertTrue(self.ipv6_address != 2) 
Example #26
Source File: ip.py    From satellite with GNU General Public License v3.0 5 votes vote down vote up
def _check_ip(net_if, ip_addr):
    """Check if interface has IP and if it matches target IP

    Args:
        net_if  : DVB network interface name
        ip_addr : Target IP address for the DVB interface slash subnet mask

    Returns:
        (Bool, Bool) Tuple of booleans. The first indicates whether interface
        already has an IP. The second indicates whether the interface IP (if
        existing) matches with respect to a target IP.

    """
    try:
        res = subprocess.check_output(["ip", "addr", "show", "dev", net_if],
                                      stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError as e:
        return False, False

    has_ip = False
    ip_ok  = False
    for line in res.splitlines():
        if "inet" in line.decode() and "inet6" not in line.decode():
            has_ip    = True
            # Check if IP matches target
            inet_info = line.decode().split()
            inet_if   = IPv4Interface(inet_info[1])
            target_if = IPv4Interface(ip_addr)
            ip_ok     = (inet_if == target_if)
            break

    return has_ip, ip_ok 
Example #27
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 testGetSupernet(self):
        self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
        self.assertEqual(str(self.ipv4_network.supernet().network_address),
                         '1.2.2.0')
        self.assertEqual(
            ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
            ipaddress.IPv4Network('0.0.0.0/0'))

        self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
        self.assertEqual(str(self.ipv6_network.supernet().network_address),
                         '2001:658:22a:cafe::')
        self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
                         ipaddress.IPv6Network('::0/0')) 
Example #28
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 testZeroNetmask(self):
        ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0')
        self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0)
        self.assertEqual(ipv4_zero_netmask._prefix_from_prefix_string('0'), 0)
        self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0'))
        self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0'))
        self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid'))

        ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0')
        self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0)
        self.assertEqual(ipv6_zero_netmask._prefix_from_prefix_string('0'), 0) 
Example #29
Source File: net.py    From pyatv with MIT License 5 votes vote down vote up
def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]:
    """Get address of a local interface within same subnet as provided address."""
    for iface in netifaces.interfaces():
        for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []):
            iface = IPv4Interface(addr["addr"] + "/" + addr["netmask"])
            if dest_ip in iface.network:
                return iface.ip
    return None 
Example #30
Source File: test_ipaddress.py    From android_universal with MIT License 5 votes vote down vote up
def testSlash32Constructor(self):
        self.assertEqual(str(ipaddress.IPv4Interface(
                    '1.2.3.4/255.255.255.255')), '1.2.3.4/32')