Return the Ethernet and IP+mask addresses assigned to a
        given interface on a node.
3702
def getInterfaceAddresses(self, node, interface):
        '''
        
        '''
        intf = self.getNode(node)['nodeobj'].getInterface(interface)
        return intf.ethaddr,intf.ipaddr,intf.netmask
284757
function listNetInterfaces() {
    return new Promise((ac, rj) => {
        exec('nmcli d', (err, stdout, stderr) => {
            const lines = stdout.split('\n');
            if (err || lines.length<2) {
                rj({error: 'No network available.'});
                return;
            }

            lines.shift();
            // Correct visible APs should be listed
            let bWlanExist = false;
            const interfaces = [];
            lines.forEach((line)=>{
                let sp = line.trim().split(/\s+/);
                if (sp.length < 4 || sp[0]=='lo') return; // Illegally formatted line
                if (sp[0].indexOf('wlan')==0) bWlanExist = true;
                interfaces.push(sp[0]);
            });

            ac([interfaces, bWlanExist]);
        });
    });
}
186072
def list_nics(nic_type=None):
    """"""
    if isinstance(nic_type, six.string_types):
        int_types = [nic_type]
    else:
        int_types = nic_type

    interfaces = []
    if nic_type:
        for int_type in int_types:
            cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
            ip_output = subprocess.check_output(cmd).decode('UTF-8')
            ip_output = ip_output.split('\n')
            ip_output = (line for line in ip_output if line)
            for line in ip_output:
                if line.split()[1].startswith(int_type):
                    matched = re.search('.*: (' + int_type +
                                        r'[0-9]+\.[0-9]+)@.*', line)
                    if matched:
                        iface = matched.groups()[0]
                    else:
                        iface = line.split()[1].replace(":", "")

                    if iface not in interfaces:
                        interfaces.append(iface)
    else:
        cmd = ['ip', 'a']
        ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
        ip_output = (line.strip() for line in ip_output if line)

        key = re.compile(r'^[0-9]+:\s+(.+):')
        for line in ip_output:
            matched = re.search(key, line)
            if matched:
                iface = matched.group(1)
                iface = iface.partition("@")[0]
                if iface not in interfaces:
                    interfaces.append(iface)

    return interfaces
848555
def _find_ip4_addresses():
    
    global _ip4_addresses
    proto = socket.AF_INET
    if _ip4_addresses is None:
        _ip4_addresses = []

        #
        # Determine the interface for the default gateway
        # (if any) and, later, prioritise the INET address on
        # that interface.
        #
        default_gateway = netifaces.gateways()['default']
        if proto in default_gateway:
            _, default_gateway_interface = default_gateway[proto]
        else:
            default_gateway_interface = None

        for interface in netifaces.interfaces():
            for info in netifaces.ifaddresses(interface).get(netifaces.AF_INET, []):
                if info['addr']:
                    if interface == default_gateway_interface:
                        _ip4_addresses.insert(0, info['addr'])
                    else:
                        _ip4_addresses.append(info['addr'])

    return _ip4_addresses
480934
def get_ips(linode_id=None):
    '''
    
    '''
    if linode_id:
        ips = _query('linode', 'ip.list', args={'LinodeID': linode_id})
    else:
        ips = _query('linode', 'ip.list')

    ips = ips['DATA']
    ret = {}

    for item in ips:
        node_id = six.text_type(item['LINODEID'])
        if item['ISPUBLIC'] == 1:
            key = 'public_ips'
        else:
            key = 'private_ips'

        if ret.get(node_id) is None:
            ret.update({node_id: {'public_ips': [], 'private_ips': []}})
        ret[node_id][key].append(item['IPADDRESS'])

    # If linode_id was specified, only return the ips, and not the
    # dictionary based on the linode ID as a key.
    if linode_id:
        _all_ips = {'public_ips': [], 'private_ips': []}
        matching_id = ret.get(six.text_type(linode_id))
        if matching_id:
            _all_ips['private_ips'] = matching_id['private_ips']
            _all_ips['public_ips'] = matching_id['public_ips']

        ret = _all_ips

    return ret
1326745
def __ip_addr(addr, address_family=socket.AF_INET):
    '''
    
    '''
    mask_max = '32'
    if address_family == socket.AF_INET6:
        mask_max = '128'

    try:
        if '/' not in addr:
            addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
    except TypeError:
        return False

    ip, mask = addr.rsplit('/', 1)

    # Verify that IP address is valid
    try:
        socket.inet_pton(address_family, ip)
    except socket.error:
        return False

    # Verify that mask is valid
    try:
        mask = int(mask)
    except ValueError:
        return False
    else:
        if not 1 <= mask <= int(mask_max):
            return False

    return True
463940
def getIPaddresses(self):
        """"""
        if not self.ipAddress:
            self.ipAddress = ipAddresses.getAll() # update with IP address
        return self.ipAddress
9627
function(hostname, callback) {
  get_nodes(function(err,nodes) {
    if (err) return callback(err);

    var n = nodes.filter(function(node) {
      return node.name === hostname;
    });

    callback(null,(n.length === 1) ? n[0].ip_address : null);
  });
}
613683
def ips(self):
        """"""
        r = []
        names = ['X_FORWARDED_FOR', 'CLIENT_IP', 'X_REAL_IP', 'X_FORWARDED', 
               'X_CLUSTER_CLIENT_IP', 'FORWARDED_FOR', 'FORWARDED', 'VIA',
               'REMOTE_ADDR']

        for name in names:
            vs = self.get_header(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

            vs = self.environ.get(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

        return r
844448
def _in6_getifaddr(ifname):
    

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError:
        log_interactive.warning("Failed to execute ifconfig.")
        return []

    # Iterate over lines and extract IPv6 addresses
    ret = []
    for line in f:
        if "inet6" in line:
            addr = line.rstrip().split(None, 2)[1]  # The second element is the IPv6 address  # noqa: E501
        else:
            continue
        if '%' in line:  # Remove the interface identifier if present
            addr = addr.split("%", 1)[0]

        # Check if it is a valid IPv6 address
        try:
            inet_pton(socket.AF_INET6, addr)
        except (socket.error, ValueError):
            continue

        # Get the scope and keep the address
        scope = in6_getscope(addr)
        ret.append((addr, scope, ifname))

    return ret
544793
def _ipconfig_getnode():
    """"""
    import os, re
    dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
    try:
        import ctypes
        buffer = ctypes.create_string_buffer(300)
        ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)  # @UndefinedVariable
        dirs.insert(0, buffer.value.decode('mbcs'))
    except:
        pass
    for dir in dirs:
        try:
            pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
        except IOError:
            continue
        for line in pipe:
            value = line.split(':')[-1].strip().lower()
            if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
                return int(value.replace('-', ''), 16)
843648
def _list_interface_private_addrs(eni_desc):
    '''
    
    '''
    primary = eni_desc.get('privateIpAddress')
    if not primary:
        return None

    addresses = [primary]

    lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
    if not isinstance(lst, list):
        return addresses

    for entry in lst:
        if entry.get('primary') == 'true':
            continue
        if entry.get('privateIpAddress'):
            addresses.append(entry.get('privateIpAddress'))

    return addresses
987285
def interface_lookup(interfaces, hwaddr, address_type):
    """"""
    for interface in interfaces.values():
        if interface.get('hwaddr') == hwaddr:
            for address in interface.get('addrs'):
                if address.get('type') == address_type:
                    return address.get('addr')
688855
def _find_interfaces_mac(ip):  # pylint: disable=invalid-name
    '''
    
    '''
    all_interfaces = _get_mine('net.interfaces')
    all_ipaddrs = _get_mine('net.ipaddrs')

    for device, device_ipaddrs in six.iteritems(all_ipaddrs):
        if not device_ipaddrs.get('result', False):
            continue
        for interface, interface_ipaddrs in six.iteritems(device_ipaddrs.get('out', {})):
            ip_addresses = interface_ipaddrs.get('ipv4', {}).keys()
            ip_addresses.extend(interface_ipaddrs.get('ipv6', {}).keys())
            for ipaddr in ip_addresses:
                if ip != ipaddr:
                    continue
                interface_mac = all_interfaces.get(device, {}).get('out', {}).get(interface, {}).get('mac_address', '')
                return device, interface, interface_mac

    return ('', '', '')
233197
def get_alias_address(iface_name, ip_mask, gw_str, metric):
    

    # Detect the architecture
    if scapy.consts.IS_64BITS:
        offset, name_len = 16, 40
    else:
        offset, name_len = 32, 32

    # Retrieve interfaces structures
    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', b'\0' * 4096)
    ifreq = ioctl(sck.fileno(), SIOCGIFCONF,
                  struct.pack("iL", len(names), names.buffer_info()[0]))

    # Extract interfaces names
    out = struct.unpack("iL", ifreq)[0]
    names = names.tobytes() if six.PY3 else names.tostring()
    names = [names[i:i + offset].split(b'\0', 1)[0] for i in range(0, out, name_len)]  # noqa: E501

    # Look for the IP address
    for ifname in names:
        # Only look for a matching interface name
        if not ifname.decode("utf8").startswith(iface_name):
            continue

        # Retrieve and convert addresses
        ifreq = ioctl(sck, SIOCGIFADDR, struct.pack("16s16x", ifname))
        ifaddr = struct.unpack(">I", ifreq[20:24])[0]
        ifreq = ioctl(sck, SIOCGIFNETMASK, struct.pack("16s16x", ifname))
        msk = struct.unpack(">I", ifreq[20:24])[0]

        # Get the full interface name
        ifname = plain_str(ifname)
        if ':' in ifname:
            ifname = ifname[:ifname.index(':')]
        else:
            continue

        # Check if the source address is included in the network
        if (ifaddr & msk) == ip_mask:
            sck.close()
            return (ifaddr & msk, msk, gw_str, ifname,
                    scapy.utils.ltoa(ifaddr), metric)

    sck.close()
    return
800156
def GetMacAddresses(self):
    """"""
    result = set()
    for interface in self.interfaces:
      if (interface.mac_address and
          interface.mac_address != b"\x00" * len(interface.mac_address)):
        result.add(Text(interface.mac_address.human_readable_address))
    return sorted(result)
826905
def setInterfaceAddresses(self, node, interface, mac=None, ip=None, netmask=None):
        '''
        
        '''
        if not self.hasNode(node):
            raise Exception("No such node {}".format(node))
        nobj = self.getNode(node)['nodeobj']
        if interface not in nobj:
            raise Exception("No such interface {}".format(interface))

        intf = nobj.getInterface(interface)
        if mac:
            intf.ethaddr = mac
        if ip:
            intf.ipaddr = ip
        if netmask:
            intf.netmask = netmask