Generate a dictionary mapping MAC address to Ethernet interfaces.

    Returns:
      dict, string MAC addresses mapped to the string network interface name.
550734
def _CreateInterfaceMapNetifaces(self):
    

    interfaces = {}
    for interface in netifaces.interfaces():
      af_link = netifaces.ifaddresses(interface).get(netifaces.AF_LINK, [])
      mac_address = next(iter(af_link), {}).get('addr', '')
      # In some systems this field can come with an empty string or with the
      # name of the interface when there is no MAC address associated with it.
      # Check the regex to be sure.
      if MAC_REGEX.match(mac_address):
        interfaces[mac_address] = interface
      else:
        message = 'Unable to determine MAC address for %s.'
        self.logger.warning(message, interface)
    return interfaces
426612
function getNetworkInterfaces() {
    const ret = {};
    for (const macinfo of Object.values(macs)) {
        if (!macinfo.self) {
            continue;
        }
        ret[macinfo.net] = objCpy(macinfo);
    }
    return ret;
}
873939
def get_ethernet_settings(self):
        
        uri = "{}/ethernetSettings".format(self.data["uri"])
        return self._helper.do_get(uri)
1026400
def _assemble_devinfo(self):
        '''
        
        '''
        devtype = {}
        for p in pcap_devices():
            if p.isloop:
                devtype[p.name] = InterfaceType.Loopback
            else:
                if sys.platform == 'linux':
                    st,output = subprocess.getstatusoutput(["iwconfig", p.name])
                    if "no wireless extensions" in output:
                        devtype[p.name] = InterfaceType.Wired
                    else:
                        devtype[p.name] = InterfaceType.Wireless
                elif sys.platform == 'darwin':
                    devtype[p.name] = InterfaceType.Unknown
                else:
                    devtype[p.name] = InterfaceType.Unknown

        devinfo = {}
        ifinfo = net_if_addrs()
        for devname in self._devs:
            ifaddrs = ifinfo.get(devname, None)
            if ifaddrs is None:
                log_warn("Address info for interface {} not found! (skipping)".format(devname))

            if sys.platform == 'darwin':
                layer2addrfam = socket.AddressFamily.AF_LINK
            elif sys.platform == 'linux':
                layer2addrfam = socket.AddressFamily.AF_PACKET
            else:
                raise RuntimeException("Platform not supported")

            macaddr = "00:00:00:00:00:00"
            ipaddr = mask = "0.0.0.0"
            for addrinfo in ifaddrs:
                if addrinfo.family == socket.AddressFamily.AF_INET:
                    ipaddr = IPv4Address(addrinfo.address)
                    mask = IPv4Address(addrinfo.netmask)
                elif addrinfo.family == layer2addrfam:
                    macaddr = EthAddr(addrinfo.address)

            ifnum = socket.if_nametoindex(devname)
            devinfo[devname] = Interface(devname, macaddr, ipaddr, netmask=mask, ifnum=ifnum, iftype=devtype[devname])
        return devinfo
232239
def _copy_interfaces_info(interfaces):
    '''
    
    '''
    ret = {}

    for interface in interfaces:
        _interface_attrs_cpy = set()
        for attr in ATTRS:
            if attr in interfaces[interface]:
                attr_dict = Hashabledict()
                attr_dict[attr] = repr(interfaces[interface][attr])
                _interface_attrs_cpy.add(attr_dict)
        ret[interface] = _interface_attrs_cpy

    return ret
478246
def mac(self):
        
        res = 'Port       Mac                VLAN\n'
        result = (yield from self._node._hypervisor.send('ethsw show_mac_addr_table {}'.format(self._node.name)))
        for line in result:
            mac, vlan, nio = line.replace('  ', ' ').split(' ')
            mac = mac.replace('.', '')
            mac = "{}:{}:{}:{}:{}:{}".format(
                mac[0:2],
                mac[2:4],
                mac[4:6],
                mac[6:8],
                mac[8:10],
                mac[10:12])
            for port_number, switch_nio in self._node.nios.items():
                if switch_nio.name == nio:
                    res += 'Ethernet' + str(port_number) + '  ' + mac + '  ' + vlan + '\n'
                    break
        return res
254605
def to_dict(self):
        ''''''
        d = super(TargetPort, self).to_dict()
        d['portName'] = self.port_name
        return d
687066
def get_mac_address(device_index=0):
    
    log = logging.getLogger(mod_logger + '.get_mac_address')
    command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)]
    log.info('Attempting to find a mac address at device index: {d}'.format(d=device_index))
    try:
        result = run_command(command)
    except CommandError:
        _, ex, trace = sys.exc_info()
        log.error('There was a problem running command, unable to determine mac address: {c}\n{e}'.format(
                c=command, e=str(ex)))
        return
    ipaddr = result['output'].split()
    get_next = False
    mac_address = None
    for part in ipaddr:
        if get_next:
            mac_address = part
            log.info('Found mac address: {m}'.format(m=mac_address))
            break
        if 'link' in part:
            get_next = True
    if not mac_address:
        log.info('mac address not found for device: {d}'.format(d=device_index))
    return mac_address
830726
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
    '''
    
    '''
    ret = set()

    ifaces = interface_data \
        if isinstance(interface_data, dict) \
        else interfaces()
    if interface is None:
        target_ifaces = ifaces
    else:
        target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces)
                              if k == interface])
        if not target_ifaces:
            log.error('Interface %s not found.', interface)
    for ip_info in six.itervalues(target_ifaces):
        addrs = ip_info.get(proto, [])
        addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])

        for addr in addrs:
            addr = ipaddress.ip_address(addr.get('address'))
            if not addr.is_loopback or include_loopback:
                ret.add(addr)
    return [six.text_type(addr) for addr in sorted(ret)]
381572
def _interface_configs():
    '''
    
    '''
    cmd = ['netsh', 'interface', 'ip', 'show', 'config']
    lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    ret = {}
    current_iface = None
    current_ip_list = None

    for line in lines:

        line = line.strip()
        if not line:
            current_iface = None
            current_ip_list = None
            continue

        if 'Configuration for interface' in line:
            _, iface = line.rstrip('"').split('"', 1)  # get iface name
            current_iface = {}
            ret[iface] = current_iface
            continue

        if ':' not in line:
            if current_ip_list:
                current_ip_list.append(line)
            else:
                log.warning('Cannot parse "%s"', line)
            continue

        key, val = line.split(':', 1)
        key = key.strip()
        val = val.strip()

        lkey = key.lower()
        if ('dns servers' in lkey) or ('wins servers' in lkey):
            current_ip_list = []
            current_iface[key] = current_ip_list
            current_ip_list.append(val)

        elif 'ip address' in lkey:
            current_iface.setdefault('ip_addrs', []).append({key: val})

        elif 'subnet prefix' in lkey:
            subnet, _, netmask = val.split(' ', 2)
            last_ip = current_iface['ip_addrs'][-1]
            last_ip['Subnet'] = subnet.strip()
            last_ip['Netmask'] = netmask.lstrip().rstrip(')')

        else:
            current_iface[key] = val

    return ret
1179968
def _get_network(self):
        '''
        
        '''
        data = dict()
        data['interfaces'] = salt.utils.network.interfaces()
        data['subnets'] = salt.utils.network.subnets()

        return data
33312
public static List<NetworkInterface> getNetworkInterfaces() {
        List<NetworkInterface> networkInterfaces = new LinkedList<NetworkInterface>();

        List<String> macs = getItems(EC2_METADATA_ROOT + "/network/interfaces/macs/");
        if (macs != null) {
            for (String mac : macs) {
                String key = mac.trim();
                if (key.endsWith("/")) {
                    key = key.substring(0, key.length() - 1);
                }
                networkInterfaces.add(new NetworkInterface(key));
            }
        }
        return networkInterfaces;
    }
111187
def _interfaces_ipconfig(out):
    '''
    
    '''
    ifaces = dict()
    iface = None
    adapter_iface_regex = re.compile(r'adapter (\S.+):$')

    for line in out.splitlines():
        if not line:
            continue
        # TODO what does Windows call Infiniband and 10/40gige adapters
        if line.startswith('Ethernet'):
            iface = ifaces[adapter_iface_regex.search(line).group(1)]
            iface['up'] = True
            addr = None
            continue
        if iface:
            key, val = line.split(',', 1)
            key = key.strip(' .')
            val = val.strip()
            if addr and key == 'Subnet Mask':
                addr['netmask'] = val
            elif key in ('IP Address', 'IPv4 Address'):
                if 'inet' not in iface:
                    iface['inet'] = list()
                addr = {'address': val.rstrip('(Preferred)'),
                        'netmask': None,
                        'broadcast': None}  # TODO find the broadcast
                iface['inet'].append(addr)
            elif 'IPv6 Address' in key:
                if 'inet6' not in iface:
                    iface['inet'] = list()
                # XXX What is the prefixlen!?
                addr = {'address': val.rstrip('(Preferred)'),
                        'prefixlen': None}
                iface['inet6'].append(addr)
            elif key == 'Physical Address':
                iface['hwaddr'] = val
            elif key == 'Media State':
                # XXX seen used for tunnel adaptors
                # might be useful
                iface['up'] = (val != 'Media disconnected')
176368
def interface_by_macaddr(self, macaddr):
        '''
        
        '''
        macaddr = EthAddr(macaddr)
        for devname,iface in self._devinfo.items():
            if iface.ethaddr == macaddr:
                return iface
        raise KeyError("No device has MAC address {}".format(macaddr))
152274
def _ExtractInterfaceMetadata(self, metadata):
    
    interfaces = []
    for network_interface in metadata:
      mac_address = network_interface.get('mac')
      interface = self.network_utils.GetNetworkInterface(mac_address)
      ip_addresses = []
      if interface:
        ip_addresses.extend(network_interface.get('forwardedIps', []))
        if self.ip_aliases:
          ip_addresses.extend(network_interface.get('ipAliases', []))
        if self.target_instance_ips:
          ip_addresses.extend(network_interface.get('targetInstanceIps', []))
        interfaces.append(NetworkDaemon.NetworkInterface(
            interface, ip_addresses, network_interface.get('ip', [])))
      else:
        message = 'Network interface not found for MAC address: %s.'
        self.logger.warning(message, mac_address)
    return interfaces
866869
def EnumerateInterfacesFromClient(args):
  
  del args  # Unused.

  pythoncom.CoInitialize()
  for interface in (wmi.WMI().Win32_NetworkAdapterConfiguration() or []):
    addresses = []
    for ip_address in interface.IPAddress or []:
      addresses.append(
          rdf_client_network.NetworkAddress(human_readable_address=ip_address))

    response = rdf_client_network.Interface(ifname=interface.Description)
    if interface.MACAddress:
      response.mac_address = binascii.unhexlify(
          interface.MACAddress.replace(":", ""))
    if addresses:
      response.addresses = addresses

    yield response
299625
def get_interfaces
      mac_keys = facts.keys.select { |f| f =~ /net\.interface\..*\.mac_address/ }
      names = mac_keys.map do |key|
        key.sub('net.interface.', '').sub('.mac_address', '') if facts[key] != 'none'
      end
      names.compact
    end