Python psutil.net_if_addrs() Examples

The following are 30 code examples of psutil.net_if_addrs(). 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 psutil , or try the search function .
Example #1
Source File: network_status.py    From marsnake with GNU General Public License v3.0 7 votes vote down vote up
def network_status(response):
	interfaces = psutil.net_if_addrs()

	for name, addrs in interfaces.items():
		key = common.decode2utf8(name) if common.is_python2x() else name
		status = {
			"ipv4" : "-",
			"ipv6" : "-",
			"mac" : "-"
		}
		
		for addr in addrs:
			if addr.family == socket.AF_INET:
				status["ipv4"] = addr.address

			if addr.family == socket.AF_INET6:
				status["ipv6"] = addr.address

			if addr.family == psutil.AF_LINK:
				status["mac"] = addr.address

		response["nic"][key] = status 
Example #2
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def test_ips(self):
        for name, addrs in psutil.net_if_addrs().items():
            for addr in addrs:
                if addr.family == psutil.AF_LINK:
                    self.assertEqual(addr.address, get_mac_address(name))
                elif addr.family == socket.AF_INET:
                    self.assertEqual(addr.address, get_ipv4_address(name))
                # TODO: test for AF_INET6 family

    # XXX - not reliable when having virtual NICs installed by Docker.
    # @unittest.skipIf(not which('ip'), "'ip' utility not available")
    # @unittest.skipIf(TRAVIS, "skipped on Travis")
    # def test_net_if_names(self):
    #     out = sh("ip addr").strip()
    #     nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
    #     found = 0
    #     for line in out.split('\n'):
    #         line = line.strip()
    #         if re.search(r"^\d+:", line):
    #             found += 1
    #             name = line.split(':')[1].strip()
    #             self.assertIn(name, nics)
    #     self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
    #         pprint.pformat(nics), out)) 
Example #3
Source File: OS.py    From AIOPS_PLATFORM with MIT License 6 votes vote down vote up
def getNetiAddrInfo(self):
        neti_list = []
        ipv4_list = []
        ipv6_list = []
        id_neti_list = []
        result_list = []
        neti_dict = psutil.net_if_addrs()
        for neti in neti_dict:
            neti_list.append(neti)
            id_neti_list.append('NETI-{}-{}'.format(self.os_id, neti))
            snic_list = neti_dict[neti]
            for snic in snic_list:
                if snic.family.name == 'AF_INET':
                    ipv4_list.append(snic.address)

                elif snic.family.name == 'AF_INET6':
                    ipv6_list.append(re.sub('%.*$', '', snic.address))

        result = [','.join(neti_list), ','.join(ipv4_list + ipv6_list), ','.join(id_neti_list)]
        return(result) 
Example #4
Source File: test_system.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_net_if_addrs_mac_null_bytes(self):
        # Simulate that the underlying C function returns an incomplete
        # MAC address. psutil is supposed to fill it with null bytes.
        # https://github.com/giampaolo/psutil/issues/786
        if POSIX:
            ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
        else:
            ret = [('em1', -1, '06-3d-29', None, None, None)]
        with mock.patch('psutil._psplatform.net_if_addrs',
                        return_value=ret) as m:
            addr = psutil.net_if_addrs()['em1'][0]
            assert m.called
            if POSIX:
                self.assertEqual(addr.address, '06:3d:29:00:00:00')
            else:
                self.assertEqual(addr.address, '06-3d-29-00-00-00') 
Example #5
Source File: test_system.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_net_if_addrs_mac_null_bytes(self):
        # Simulate that the underlying C function returns an incomplete
        # MAC address. psutil is supposed to fill it with null bytes.
        # https://github.com/giampaolo/psutil/issues/786
        if POSIX:
            ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
        else:
            ret = [('em1', -1, '06-3d-29', None, None, None)]
        with mock.patch('psutil._psplatform.net_if_addrs',
                        return_value=ret) as m:
            addr = psutil.net_if_addrs()['em1'][0]
            assert m.called
            if POSIX:
                self.assertEqual(addr.address, '06:3d:29:00:00:00')
            else:
                self.assertEqual(addr.address, '06-3d-29-00-00-00') 
Example #6
Source File: test_system.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_net_if_addrs_mac_null_bytes(self):
        # Simulate that the underlying C function returns an incomplete
        # MAC address. psutil is supposed to fill it with null bytes.
        # https://github.com/giampaolo/psutil/issues/786
        if POSIX:
            ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
        else:
            ret = [('em1', -1, '06-3d-29', None, None, None)]
        with mock.patch('psutil._psplatform.net_if_addrs',
                        return_value=ret) as m:
            addr = psutil.net_if_addrs()['em1'][0]
            assert m.called
            if POSIX:
                self.assertEqual(addr.address, '06:3d:29:00:00:00')
            else:
                self.assertEqual(addr.address, '06-3d-29-00-00-00') 
Example #7
Source File: system_status.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def getNetworkInfo(cls):
        interfaces = {}

        stats = psutil.net_if_stats()
        for key, value in six.iteritems(stats):
            interfaces[key] = value.__dict__
            interfaces[key]['addresses'] = []
            interfaces[key]['io_counters'] = None

        addresses = psutil.net_if_addrs()
        for key, value in six.iteritems(addresses):
            if key not in interfaces:
                continue

            for addr in value:
                interfaces[key]['addresses'].append(addr.__dict__)

        traffic = psutil.net_io_counters(pernic=True)
        for key, value in six.iteritems(traffic):
            if key not in interfaces:
                continue

            interfaces[key]['io_counters'] = value.__dict__

        return interfaces 
Example #8
Source File: addresses.py    From parsl with Apache License 2.0 6 votes vote down vote up
def get_all_addresses() -> Set[str]:
    """ Uses a combination of methods to determine possible addresses.

    Returns:
         list of addresses as strings
    """
    net_interfaces = psutil.net_if_addrs()

    s_addresses = set()
    for interface in net_interfaces:
        try:
            s_addresses.add(address_by_interface(interface))
        except Exception:
            logger.exception("Ignoring failure to fetch address from interface {}".format(interface))
            pass

    resolution_functions = [address_by_hostname, address_by_route, address_by_query]  # type: List[Callable[[], str]]
    for f in resolution_functions:
        try:
            s_addresses.add(f())
        except Exception:
            logger.exception("Ignoring an address finder exception")

    return s_addresses 
Example #9
Source File: sysinfo.py    From RTask with GNU General Public License v3.0 6 votes vote down vote up
def get_network():
    network = psutil.net_io_counters(pernic=True)
    ifaces = psutil.net_if_addrs()
    networks = list()
    for k, v in ifaces.items():
        ip = v[0].address
        data = network[k]
        ifnet = dict()
        ifnet['ip'] = ip
        ifnet['iface'] = k
        ifnet['sent'] = '%.2fMB' % (data.bytes_sent/1024/1024)
        ifnet['recv'] = '%.2fMB' % (data.bytes_recv/1024/1024)
        ifnet['packets_sent'] = data.packets_sent
        ifnet['packets_recv'] = data.packets_recv
        ifnet['errin'] = data.errin
        ifnet['errout'] = data.errout
        ifnet['dropin'] = data.dropin
        ifnet['dropout'] = data.dropout
        networks.append(ifnet)
    return networks 
Example #10
Source File: utils.py    From HoneyBot with MIT License 6 votes vote down vote up
def get_mac_address_of_interface(interface):
    """
    :param interface: The friendly name of a network interface
    :return: the MAC address associated with that interface
    """
    for k,v in psutil.net_if_addrs().items():
        if interface == k:
            for item in v:
                try:
                    if item.family == socket.AF_LINK:
                        return item.address
                except AttributeError:
                    # Linux
                    if item.family == socket.AF_PACKET:
                        return item.address
    return None 
Example #11
Source File: zynthian_config.py    From zynthian-ui with GNU General Public License v3.0 6 votes vote down vote up
def get_netinfo(exclude_down=True):
	netinfo={}
	for ifc, snics in psutil.net_if_addrs().items():
		if ifc=="lo":
			continue
		for snic in snics:
			if snic.family == socket.AF_INET:
				netinfo[ifc]=snic
		if ifc not in netinfo:
			c=0
			for snic in snics:
				if snic.family == socket.AF_INET6:
					c+=1
			if c>=2:
				netinfo[ifc]=snic
		if ifc not in netinfo and not exclude_down:
			netinfo[ifc]=None
	return netinfo 
Example #12
Source File: activity.py    From autosuspend with GNU General Public License v2.0 6 votes vote down vote up
def check(self) -> Optional[str]:
        own_addresses = [
            (item.family, item.address.split("%")[0])
            for sublist in psutil.net_if_addrs().values()
            for item in sublist
        ]
        connected = [
            c.laddr[1]
            for c in psutil.net_connections()
            if (
                (c.family, c.laddr[0]) in own_addresses
                and c.status == "ESTABLISHED"
                and c.laddr[1] in self._ports
            )
        ]
        if connected:
            return "Ports {} are connected".format(connected)
        else:
            return None 
Example #13
Source File: url_utils.py    From nni with MIT License 5 votes vote down vote up
def get_local_urls(port):
    '''get urls of local machine'''
    url_list = []
    for _, info in psutil.net_if_addrs().items():
        for addr in info:
            if socket.AddressFamily.AF_INET == addr.family:
                url_list.append('http://{}:{}'.format(addr.address, port))
    return url_list 
Example #14
Source File: test_memory_leaks.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_if_addrs(self):
        # Note: verified that on Windows this was a false positive.
        self.execute(psutil.net_if_addrs,
                     tolerance_=80 * 1024 if WINDOWS else None) 
Example #15
Source File: utils.py    From bitnodes-hardware with MIT License 5 votes vote down vote up
def get_lan_address():
    lan_address = cache.get('lan_address')
    if lan_address is None:
        for address in net_if_addrs().get(settings.NETWORK_INTERFACE):
            if address.family == AF_INET:
                lan_address = address.address
                cache.set('lan_address', lan_address, 600)
                return lan_address
    return lan_address 
Example #16
Source File: test_aix.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_if_addrs_names(self):
        out = sh('/etc/ifconfig -l')
        ifconfig_names = set(out.split())
        psutil_names = set(psutil.net_if_addrs().keys())
        self.assertSetEqual(ifconfig_names, psutil_names) 
Example #17
Source File: network.py    From rpi_lcars with MIT License 5 votes vote down vote up
def get_ip_addresses():
    """
    Returns all the IP addresses of the machine we're running on.
    Shamelessly derived from:
        https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics
    """

    ip_list = filter(
        lambda ip: ip is not None and ip != '127.0.0.1',
        [interface_to_ip(v) for v in psutil.net_if_addrs().values()])

    return ip_list 
Example #18
Source File: network.py    From rpi_lcars with MIT License 5 votes vote down vote up
def interface_to_ip(interface):
    """
    Gets the IPv4 address from a `net_if_addrs` interface record.
    The record is passed as a `snic` `namedtuple`.
    This function locates the IPv4 one and returns it.
    """
    for record in interface:
        if record.family == 2:  # AF_INET
            return record.address

    return None 
Example #19
Source File: sysinfo.py    From RTask with GNU General Public License v3.0 5 votes vote down vote up
def get_macid():
    ifaces = psutil.net_if_addrs()
    macs = list()
    for iface, info in ifaces.items():
        if iface == 'lo':
            continue
        ipv4_mac = info[-1].address
        macs.append(ipv4_mac)
    macs.sort()
    mac_str = ':'.join(macs)
    hash_str = hashlib.md5(mac_str.encode('UTF-8')).hexdigest()
    return hash_str 
Example #20
Source File: test_contracts.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_if_addrs(self):
        # Duplicate of test_system.py. Keep it anyway.
        for ifname, addrs in psutil.net_if_addrs().items():
            self.assertIsInstance(ifname, str)
            for addr in addrs:
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None))) 
Example #21
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def test_no_activity(self, serve_data_url) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), sys.float_info.max, sys.float_info.max
        )
        # make some traffic
        requests.get(serve_data_url)
        assert check.check() is None 
Example #22
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def test_with_activity(
        self, send_threshold, receive_threshold, match, serve_data_url
    ) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), send_threshold, receive_threshold
        )
        # make some traffic
        requests.get(serve_data_url)
        res = check.check()
        assert res is not None
        assert match in res 
Example #23
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def _mock_interfaces(self, mocker):
        mock = mocker.patch("psutil.net_if_addrs")
        mock.return_value = {"foo": None, "bar": None, "baz": None} 
Example #24
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def create_instance(self, name):
        return NetworkBandwidth(name, psutil.net_if_addrs().keys(), 0, 0) 
Example #25
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def test_not_connected(self, monkeypatch, connection) -> None:
        def addresses():
            return {
                "dummy": [
                    snic(socket.AF_INET, self.MY_ADDRESS, "255.255.255.0", None, None)
                ]
            }

        def connections():
            return [connection]

        monkeypatch.setattr(psutil, "net_if_addrs", addresses)
        monkeypatch.setattr(psutil, "net_connections", connections)

        assert ActiveConnection("foo", [10, self.MY_PORT, 30]).check() is None 
Example #26
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def test_connected(self, monkeypatch, connection) -> None:
        def addresses():
            return {
                "dummy": [
                    snic(socket.AF_INET, self.MY_ADDRESS, "255.255.255.0", None, None),
                    snic(
                        socket.AF_INET6,
                        self.MY_ADDRESS_IPV6,
                        "ffff:ffff:ffff:ffff::",
                        None,
                        None,
                    ),
                    snic(
                        socket.AF_INET6,
                        self.MY_ADDRESS_IPV6_SCOPED,
                        "ffff:ffff:ffff:ffff::",
                        None,
                        None,
                    ),
                ],
            }

        def connections():
            return [connection]

        monkeypatch.setattr(psutil, "net_if_addrs", addresses)
        monkeypatch.setattr(psutil, "net_connections", connections)

        assert ActiveConnection("foo", [10, self.MY_PORT, 30]).check() is not None 
Example #27
Source File: activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def create(
        cls, name: str, config: configparser.SectionProxy,
    ) -> "NetworkBandwidth":
        try:
            interfaces = config["interfaces"].split(",")
            interfaces = [i.strip() for i in interfaces if i.strip()]
            if not interfaces:
                raise ConfigurationError("No interfaces configured")
            host_interfaces = psutil.net_if_addrs().keys()
            for interface in interfaces:
                if interface not in host_interfaces:
                    raise ConfigurationError(
                        "Network interface {} does not exist".format(interface)
                    )
            threshold_send = config.getfloat("threshold_send", fallback=100)
            threshold_receive = config.getfloat("threshold_receive", fallback=100)
            return cls(name, interfaces, threshold_send, threshold_receive)
        except KeyError as error:
            raise ConfigurationError(
                "Missing configuration key: {}".format(error)
            ) from error
        except ValueError as error:
            raise ConfigurationError(
                "Threshold in wrong format: {}".format(error)
            ) from error 
Example #28
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_if_names(self):
        out = sh("ip addr").strip()
        nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
        found = 0
        for line in out.split('\n'):
            line = line.strip()
            if re.search(r"^\d+:", line):
                found += 1
                name = line.split(':')[1].strip()
                self.assertIn(name, nics)
        self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
            pprint.pformat(nics), out)) 
Example #29
Source File: NETI.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def getNetiInfo(self):
        result = []
        neti_dict = psutil.net_if_addrs()
        for neti in neti_dict:
            ipv4_ip = ''
            ipv6_ip = ''
            ipv4_netmask = ''
            ipv6_netmask = ''
            mac = ''

            snic_list = neti_dict[neti]
            for snic in snic_list:
                if snic.family.name == 'AF_INET':
                    ipv4_ip = snic.address
                    ipv4_netmask = snic.netmask

                elif snic.family.name == 'AF_INET6':
                    ipv6_ip = re.sub('%.*$', '', snic.address)
                    ipv6_netmask = snic.netmask

                elif snic.family.name == 'AF_PACKET':
                    mac = snic.address

            result.append([neti, ipv4_ip, ipv6_ip, ipv4_netmask,
                            ipv6_netmask, mac])
        
        return(result)

    ## get Neti Status 
Example #30
Source File: test_checks_activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def test_internal_state_updated(self, serve_data_url) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), sys.float_info.max, sys.float_info.max
        )
        check.check()
        old_state = check._previous_values
        requests.get(serve_data_url)
        check.check()
        assert old_state != check._previous_values