我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用netifaces.ifaddresses()。
def _get_ipv6_network_from_address(address): """Get an netaddr.IPNetwork for the given IPv6 address :param address: a dict as returned by netifaces.ifaddresses :returns netaddr.IPNetwork: None if the address is a link local or loopback address """ if address['addr'].startswith('fe80') or address['addr'] == "::1": return None prefix = address['netmask'].split("/") if len(prefix) > 1: netmask = prefix[1] else: netmask = address['netmask'] return netaddr.IPNetwork("%s/%s" % (address['addr'], netmask))
def get_iface_from_addr(addr): """Work out on which interface the provided address is configured.""" for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) for inet_type in addresses: for _addr in addresses[inet_type]: _addr = _addr['addr'] # link local ll_key = re.compile("(.+)%.*") raw = re.match(ll_key, _addr) if raw: _addr = raw.group(1) if _addr == addr: log("Address '%s' is configured on iface '%s'" % (addr, iface)) return iface msg = "Unable to infer net iface on which '%s' is configured" % (addr) raise Exception(msg)
def ipv4(): """ Get all IPv4 addresses for all interfaces. """ try: from netifaces import interfaces, ifaddresses, AF_INET # to not take into account loopback addresses (no interest here) addresses = [] for interface in interfaces(): config = ifaddresses(interface) # AF_INET is not always present if AF_INET in config.keys(): for link in config[AF_INET]: # loopback holds a 'peer' instead of a 'broadcast' address if 'addr' in link.keys() and 'peer' not in link.keys(): addresses.append(link['addr']) return addresses except ImportError: return []
def network(interface=None): if interface: try: netifaces.ifaddresses(interface) interfaces = [interface] except ValueError: return jsonify({"message": "interface {} not available".format(interface)}), 404 else: interfaces = netifaces.interfaces() data = dict() for i in interfaces: try: data[i] = netifaces.ifaddresses(i)[2] except KeyError: data[i] = {"message": "AF_INET data missing"} return jsonify(data)
def __init__(self, data # Data suitable for this class ): valid, message = data_is_valid(data) if not valid: raise ValueError("Invalid data: %s" % message) self.cidrs = [] for iface in netifaces.interfaces(): ifaddrs = netifaces.ifaddresses(iface) if netifaces.AF_INET in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET]: if 'addr' in ifaddr: self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'])) if netifaces.AF_INET6 in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET6]: if 'addr' in ifaddr: #add v6 but remove stuff like %eth0 that gets thrown on end of some addrs self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'].split('%')[0]))
def get_host_devices(iface_prefix=''): rst = {} for ifacename in netifaces.interfaces(): if not ifacename.startswith(iface_prefix): continue addrs = netifaces.ifaddresses(ifacename) if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs: ips = [addr['addr'] for addr in addrs[netifaces.AF_INET]] for ip in ips: if is_ip4_loopback(ip): break else: rst[ifacename] = {'INET': addrs[netifaces.AF_INET], 'LINK': addrs[netifaces.AF_LINK]} return rst
def get_interface_addresses(logger): import StaticUPnP_Settings interface_config = Namespace(**StaticUPnP_Settings.interfaces) ip_addresses = StaticUPnP_Settings.ip_addresses if len(ip_addresses) == 0: import netifaces ifs = netifaces.interfaces() if len(interface_config.include) > 0: ifs = interface_config.include if len(interface_config.exclude) > 0: for iface in interface_config.exclude: ifs.remove(iface) for i in ifs: addrs = netifaces.ifaddresses(i) if netifaces.AF_INET in addrs: for addr in addrs[netifaces.AF_INET]: ip_addresses.append(addr['addr']) logger.info("Regestering multicast on %s: %s"%(i, addr['addr'])) return ip_addresses
def internal_ip(pl, interface='auto', ipv=4): family = netifaces.AF_INET6 if ipv == 6 else netifaces.AF_INET if interface == 'auto': try: interface = next(iter(sorted(netifaces.interfaces(), key=_interface_key, reverse=True))) except StopIteration: pl.info('No network interfaces found') return None elif interface == 'default_gateway': try: interface = netifaces.gateways()['default'][family][1] except KeyError: pl.info('No default gateway found for IPv{0}', ipv) return None addrs = netifaces.ifaddresses(interface) try: return addrs[family][0]['addr'] except (KeyError, IndexError): pl.info("No IPv{0} address found for interface {1}", ipv, interface) return None
def _get_my_ipv4_address(): """Figure out the best ipv4 """ LOCALHOST = '127.0.0.1' gtw = netifaces.gateways() try: interface = gtw['default'][netifaces.AF_INET][1] except (KeyError, IndexError): LOG.info(_LI('Could not determine default network interface, ' 'using 127.0.0.1 for IPv4 address')) return LOCALHOST try: return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] except (KeyError, IndexError): LOG.info(_LI('Could not determine IPv4 address for interface %s, ' 'using 127.0.0.1'), interface) except Exception as e: LOG.info(_LI('Could not determine IPv4 address for ' 'interface %(interface)s: %(error)s'), {'interface': interface, 'error': e}) return LOCALHOST
def get_ip_address(iface): """Get IP address of the interface connected to the network. If there is no such an interface, then localhost is returned. """ if iface not in netifaces.interfaces(): LOG.warning("Can't find interface '%s' in the host list of interfaces", iface) return '127.0.0.1' address_family = netifaces.AF_INET if address_family not in netifaces.ifaddresses(iface): LOG.warning("Interface '%s' doesnt configured with ipv4 address", iface) return '127.0.0.1' for ifaddress in netifaces.ifaddresses(iface)[address_family]: if 'addr' in ifaddress: return ifaddress['addr'] else: LOG.warning("Can't find ip addr for interface '%s'", iface) return '127.0.0.1'
def extract_ipv6_info(): """ Extracts IPv6 information""" print ("IPv6 support built into Python: %s" %socket.has_ipv6) for interface in ni.interfaces(): all_addresses = ni.ifaddresses(interface) print ("Interface %s:" %interface) for family,addrs in all_addresses.items(): fam_name = ni.address_families[family] for addr in addrs: if fam_name == 'AF_INET6': addr = addr['addr'] has_eth_string = addr.split("%eth") if has_eth_string: addr = addr.split("%eth")[0] try: print (" IP Address: %s" %na.IPNetwork(addr)) print (" IP Version: %s" %na.IPNetwork(addr).version) print (" IP Prefix length: %s" %na.IPNetwork(addr).prefixlen) print (" Network: %s" %na.IPNetwork(addr).network) print (" Broadcast: %s" %na.IPNetwork(addr).broadcast) except Exception as e: print ("Skip Non-IPv6 Interface")
def inspect_ipv6_support(): """ Find the ipv6 address""" print ("IPV6 support built into Python: %s" %socket.has_ipv6) ipv6_addr = {} for interface in ni.interfaces(): all_addresses = ni.ifaddresses(interface) print ("Interface %s:" %interface) for family,addrs in all_addresses.items(): fam_name = ni.address_families[family] print (' Address family: %s' % fam_name) for addr in addrs: if fam_name == 'AF_INET6': ipv6_addr[interface] = addr['addr'] print (' Address : %s' % addr['addr']) nmask = addr.get('netmask', None) if nmask: print (' Netmask : %s' % nmask) bcast = addr.get('broadcast', None) if bcast: print (' Broadcast: %s' % bcast) if ipv6_addr: print ("Found IPv6 address: %s" %ipv6_addr) else: print ("No IPv6 interface found!")
def in6_getifaddr(): """ Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'ifcace'. This is the list of all addresses of all interfaces available on the system. """ ret = [] interfaces = get_if_list() for i in interfaces: addrs = netifaces.ifaddresses(i) if netifaces.AF_INET6 not in addrs: continue for a in addrs[netifaces.AF_INET6]: addr = a['addr'].split('%')[0] scope = scapy.utils6.in6_getscope(addr) ret.append((addr, scope, i)) return ret
def get_lo_alias_addr(): # check all interfaces an try to find one with address 127.0.0.1 # If that interface has another address, that's the one we need. ifname_loopback = None for interface in netifaces.interfaces(): ip_addresses = [] interface_addresses = netifaces.ifaddresses(interface) if netifaces.AF_INET not in interface_addresses: continue for address_data in interface_addresses[netifaces.AF_INET]: if address_data.get('addr') == '127.0.0.1': ifname_loopback = interface elif address_data.get('addr'): ip_addresses.append(address_data.get('addr')) if interface == ifname_loopback and ip_addresses: return ip_addresses[0]