Given a MAC address, return the interface that 'owns' this address
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))
961361
public static byte[] bestAvailableMac() {
        // Find the best MAC address available.
        byte[] bestMacAddr = EMPTY_BYTES;
        InetAddress bestInetAddr = NetUtil.LOCALHOST4;

        // Retrieve the list of available network interfaces.
        Map<NetworkInterface, InetAddress> ifaces = new LinkedHashMap<NetworkInterface, InetAddress>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    NetworkInterface iface = interfaces.nextElement();
                    // Use the interface with proper INET addresses only.
                    Enumeration<InetAddress> addrs = SocketUtils.addressesFromNetworkInterface(iface);
                    if (addrs.hasMoreElements()) {
                        InetAddress a = addrs.nextElement();
                        if (!a.isLoopbackAddress()) {
                            ifaces.put(iface, a);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.warn("Failed to retrieve the list of available network interfaces", e);
        }

        for (Entry<NetworkInterface, InetAddress> entry: ifaces.entrySet()) {
            NetworkInterface iface = entry.getKey();
            InetAddress inetAddr = entry.getValue();
            if (iface.isVirtual()) {
                continue;
            }

            byte[] macAddr;
            try {
                macAddr = SocketUtils.hardwareAddressFromNetworkInterface(iface);
            } catch (SocketException e) {
                logger.debug("Failed to get the hardware address of a network interface: {}", iface, e);
                continue;
            }

            boolean replace = false;
            int res = compareAddresses(bestMacAddr, macAddr);
            if (res < 0) {
                // Found a better MAC address.
                replace = true;
            } else if (res == 0) {
                // Two MAC addresses are of pretty much same quality.
                res = compareAddresses(bestInetAddr, inetAddr);
                if (res < 0) {
                    // Found a MAC address with better INET address.
                    replace = true;
                } else if (res == 0) {
                    // Cannot tell the difference.  Choose the longer one.
                    if (bestMacAddr.length < macAddr.length) {
                        replace = true;
                    }
                }
            }

            if (replace) {
                bestMacAddr = macAddr;
                bestInetAddr = inetAddr;
            }
        }

        if (bestMacAddr == EMPTY_BYTES) {
            return null;
        }

        switch (bestMacAddr.length) {
            case EUI48_MAC_ADDRESS_LENGTH: // EUI-48 - convert to EUI-64
                byte[] newAddr = new byte[EUI64_MAC_ADDRESS_LENGTH];
                System.arraycopy(bestMacAddr, 0, newAddr, 0, 3);
                newAddr[3] = (byte) 0xFF;
                newAddr[4] = (byte) 0xFE;
                System.arraycopy(bestMacAddr, 3, newAddr, 5, 3);
                bestMacAddr = newAddr;
                break;
            default: // Unknown
                bestMacAddr = Arrays.copyOf(bestMacAddr, EUI64_MAC_ADDRESS_LENGTH);
        }

        return bestMacAddr;
    }
627372
def get_device_mac(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/sys/class/net/wlan0/address')
        return output.strip()
951669
def source_mac
      @source_mac ||= if self.victim_ip
        ::ServiceObjects::NetworkInformation.self_mac(interface)
      else
        gateway_ip = ServiceObjects::NetworkInformation.gateway_ip
        mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip)
      end
    end
1022381
function getHostname()
{
  var interfaces = networkInterfaces()
  for(var name in interfaces)
  {
    var info = interfaces[name].filter(filterIPv4)[0]
    if(info) return info.address
  }
}
328463
def _getdevicetuple(iobtdevice):
    
    addr = _macutil.formatdevaddr(iobtdevice.getAddressString())
    name = iobtdevice.getName()
    cod = iobtdevice.getClassOfDevice()
    return (addr, name, cod)
765498
def set_mac_addr(self, mac_addr):
        

        yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform,
                                                                                              name=self._name,
                                                                                              mac_addr=mac_addr))

        log.info('Router "{name}" [{id}]: MAC address updated from {old_mac} to {new_mac}'.format(name=self._name,
                                                                                                  id=self._id,
                                                                                                  old_mac=self._mac_addr,
                                                                                                  new_mac=mac_addr))
        self._mac_addr = mac_addr
587136
def get_host_mac(name=None, allow_array=False, **api_opts):
    '''
    
    '''
    data = get_host(name=name, **api_opts)
    if data and 'ipv4addrs' in data:
        l = []
        for a in data['ipv4addrs']:
            if 'mac' in a:
                l.append(a['mac'])
        if allow_array:
            return l
        if l:
            return l[0]
    return None
813580
def get_iface_from_addr(addr):
    """"""
    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)
1180020
def mac_addr=(val)
      state = val ? '' : 'no'
      mac = val ? val.tr(':', '').scan(/.{1,4}/).join('.') : ''
      set_args_keys(state: state, mac: mac)
      config_set('interface_hsrp_group', 'mac_addr', @set_args)
    end
135694
function getAnnouncedIpsForInterface(ifaceName) {
	const addresses = interfaces[ifaceName];

	if (!addresses) {
		throw new Error('Interface ' + ifaceName + ' could not be found');
	}

	const announced = pushIps(addresses, [], true);
	assertNotEmpty(announced, 'Interface ' + ifaceName + ' does not define any IP addresses');

	return announced;
}
554962
def _hunt_for_mac(to_find, type_of_thing, net_ok=True):
    # type: (Optional[str], int, bool) -> Optional[str]
    
    if to_find is None:
        log.warning("_hunt_for_mac() failed: to_find is None")
        return None
    if not PY2 and isinstance(to_find, bytes):
        to_find = str(to_find, 'utf-8')

    if WINDOWS and type_of_thing == INTERFACE:
        methods = [
            # getmac - Connection Name
            (r'\r\n' + to_find + r'.*' + MAC_RE_DASH + r'.*\r\n',
             0, 'getmac.exe', ['/NH /V']),

            # ipconfig
            (to_find + r'(?:\n?[^\n]*){1,8}Physical Address[ .:]+' + MAC_RE_DASH + r'\r\n',
             0, 'ipconfig.exe', ['/all']),

            # getmac - Network Adapter (the human-readable name)
            (r'\r\n.*' + to_find + r'.*' + MAC_RE_DASH + r'.*\r\n',
             0, 'getmac.exe', ['/NH /V']),

            # wmic - WMI command line utility
            lambda x: _popen('wmic.exe', 'nic where "NetConnectionID = \'%s\'" get '
                                         'MACAddress /value' % x).strip().partition('=')[2],
        ]
    elif (WINDOWS or WSL) and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            # arp -a - Parsing result with a regex
            (MAC_RE_DASH, 0, 'arp.exe', ['-a %s' % to_find]),
        ]

        # Add methods that make network requests
        # Insert it *after* arp.exe since that's probably faster.
        if net_ok and type_of_thing != IP6 and not WSL:
            methods.insert(1, _windows_ctypes_host)
    elif (DARWIN or FREEBSD) and type_of_thing == INTERFACE:
        methods = [
            (r'ether ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # Alternative match for ifconfig if it fails
            (to_find + r'.*ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['']),

            (MAC_RE_COLON,
             0, 'networksetup', ['-getmacaddress %s' % to_find]),
        ]
    elif FREEBSD and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            (r'\(' + re.escape(to_find) + r'\)\s+at\s+' + MAC_RE_COLON,
             0, 'arp', [to_find])
        ]
    elif OPENBSD and type_of_thing == INTERFACE:
        methods = [
            (r'lladdr ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),
        ]
    elif OPENBSD and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            (re.escape(to_find) + r'[ ]+' + MAC_RE_COLON,
             0, 'arp', ['-an']),
        ]
    elif type_of_thing == INTERFACE:
        methods = [
            _read_sys_iface_file,
            _fcntl_iface,

            # Fast modern Ubuntu ifconfig
            (r'ether ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # Fast ifconfig
            (r'HWaddr ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # ip link (Don't use 'list' due to SELinux [Android 24+])
            (to_find + r'.*\n.*link/ether ' + MAC_RE_COLON,
             0, 'ip', ['link %s' % to_find, 'link']),

            # netstat
            (to_find + r'.*HWaddr ' + MAC_RE_COLON,
             0, 'netstat', ['-iae']),

            # More variations of ifconfig
            (to_find + r'.*ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['']),
            (to_find + r'.*HWaddr ' + MAC_RE_COLON,
             0, 'ifconfig', ['', '-a', '-v']),

            # Tru64 ('-av')
            (to_find + r'.*Ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['-av']),
            _uuid_lanscan_iface,
        ]
    elif type_of_thing in [IP4, IP6, HOSTNAME]:
        esc = re.escape(to_find)
        methods = [
            _read_arp_file,
            lambda x: _popen('ip', 'neighbor show %s' % x)
            .partition(x)[2].partition('lladdr')[2].strip().split()[0],

            (r'\(' + esc + r'\)\s+at\s+' + MAC_RE_COLON,
             0, 'arp', [to_find, '-an', '-an %s' % to_find]),

            # Darwin oddness
            (r'\(' + esc + r'\)\s+at\s+' + MAC_RE_DARWIN,
             0, 'arp', [to_find, '-a', '-a %s' % to_find]),
            _uuid_ip,
        ]
    else:
        log.critical("Reached end of _hunt_for_mac() if-else chain!")
        return None
    return _try_methods(methods, to_find)
109787
def get_if_raw_hwaddr(ifname):
    """"""

    NULL_MAC_ADDRESS = b'\x00' * 6

    # Handle the loopback interface separately
    if ifname == LOOPBACK_NAME:
        return (ARPHDR_LOOPBACK, NULL_MAC_ADDRESS)

    # Get ifconfig output
    try:
        fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg)

    # Get MAC addresses
    addresses = [l for l in fd.readlines() if l.find("ether") >= 0 or
                 l.find("lladdr") >= 0 or
                 l.find("address") >= 0]
    if not addresses:
        raise Scapy_Exception("No MAC address found on %s !" % ifname)

    # Pack and return the MAC address
    mac = addresses[0].split(' ')[1]
    mac = [chr(int(b, 16)) for b in mac.split(':')]
    return (ARPHDR_ETHER, ''.join(mac))
983666
def _get_interface_info(interface):
    '''
    
    '''
    adapter_mode = _get_adapter_mode_info(interface.name)
    if adapter_mode == 'disabled':
        return _get_base_interface_info(interface)
    elif adapter_mode == 'ethercat':
        return _get_ethercat_interface_info(interface)
    return _get_tcpip_interface_info(interface)
460117
def get_mac(self, use_cached=True):
        """"""
        device_json = self.get_device_json(use_cached)
        return device_json.get("devMac")
684087
def RemoveForwardedIp(self, address, interface):
    
    ip = netaddr.IPNetwork(address)
    self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])
44772
def _get_primary_address(self, mac_address, node_list):
        
        for local_addresses in node_list:
            if mac_address in local_addresses:
                return local_addresses[0]
        return mac_address