Uses ifconfig to return a dictionary of interfaces with various information
    about each (up/down state, ip address, netmask, and hwaddr)
187648
def _interfaces_ifconfig(out):
    
    ret = dict()

    piface = re.compile(r'^([^\s:]+)')
    pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
    pip = re.compile(r'.*?(?:inet addr:|inet )(.*?)\s')
    pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
    pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
    pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+)).*')
    pupdown = re.compile('UP')
    pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')

    groups = re.compile('\r?\n(?=\\S)').split(out)
    for group in groups:
        data = dict()
        iface = ''
        updown = False
        for line in group.splitlines():
            miface = piface.match(line)
            mmac = pmac.match(line)
            mip = pip.match(line)
            mip6 = pip6.match(line)
            mupdown = pupdown.search(line)
            if miface:
                iface = miface.group(1)
            if mmac:
                data['hwaddr'] = mmac.group(1)
            if mip:
                if 'inet' not in data:
                    data['inet'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip.group(1)
                mmask = pmask.match(line)
                if mmask:
                    if mmask.group(1):
                        mmask = _number_of_set_bits_to_ipv4_netmask(
                            int(mmask.group(1), 16))
                    else:
                        mmask = mmask.group(2)
                    addr_obj['netmask'] = mmask
                mbcast = pbcast.match(line)
                if mbcast:
                    addr_obj['broadcast'] = mbcast.group(1)
                data['inet'].append(addr_obj)
            if mupdown:
                updown = True
            if mip6:
                if 'inet6' not in data:
                    data['inet6'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip6.group(1) or mip6.group(2)
                mmask6 = pmask6.match(line)
                if mmask6:
                    addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
                data['inet6'].append(addr_obj)
        data['up'] = updown
        ret[iface] = data
        del data
    return ret
654409
def fake_getaddrinfo(
        host, port, family=None, socktype=None, proto=None, flags=None):
    """"""
    return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP,
             '', (host, port))]
911989
def GetForwardedIps(self, interface, interface_ip=None):
    
    try:
      ips = netifaces.ifaddresses(interface)
      ips = ips[netifaces.AF_INET]
    except (ValueError, IndexError):
      return []
    forwarded_ips = []
    for ip in ips:
      if ip['addr'] != interface_ip:
        full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())
        forwarded_ips.append(full_addr)
    return self.ParseForwardedIps(forwarded_ips)
476220
def _get_interfaces(self):
        
        ios_cfg = self._get_running_config()
        parse = HTParser(ios_cfg)
        itfcs_raw = parse.find_lines("^interface GigabitEthernet")
        itfcs = [raw_if.strip().split(' ')[1] for raw_if in itfcs_raw]
        LOG.debug("Interfaces on hosting device: %s", itfcs)
        return itfcs
866363
def _find_interfaces_ip(mac):
    '''
    
    '''
    try:
        mac = napalm_helpers.convert(napalm_helpers.mac, mac)
    except AddrFormatError:
        return ('', '', [])

    all_interfaces = _get_mine('net.interfaces')
    all_ipaddrs = _get_mine('net.ipaddrs')

    for device, device_interfaces in six.iteritems(all_interfaces):
        if not device_interfaces.get('result', False):
            continue
        for interface, interface_details in six.iteritems(device_interfaces.get('out', {})):
            try:
                interface_mac = napalm_helpers.convert(napalm_helpers.mac, interface_details.get('mac_address'))
            except AddrFormatError:
                continue
            if mac != interface_mac:
                continue
            interface_ipaddrs = all_ipaddrs.get(device, {}).get('out', {}).get(interface, {})
            ip_addresses = interface_ipaddrs.get('ipv4', {})
            ip_addresses.update(interface_ipaddrs.get('ipv6', {}))
            interface_ips = ['{0}/{1}'.format(ip_addr,
                                              addr_details.get('prefix_length', '32'))
                             for ip_addr, addr_details in six.iteritems(ip_addresses)]
            return device, interface, interface_ips

    return ('', '', [])
1211849
def interfaces(self):
        
        if 'interfaces' not in self._cached_values:
            self._cached_values['interfaces'] = []
            for name, interface in six.iteritems(self.settings.INTERFACES):
                interface_name = 'interface_%s' % name
                # Hostname:port + unix socket
                try:
                    listen = self.config_parser.get(interface_name, 'Listen')
                except CONFIGPARSER_EXC:
                    listen = interface.get('LISTEN')
                try:
                    unix_socket = self.config_parser.get(
                        interface_name, 'UnixSocket')
                except CONFIGPARSER_EXC:
                    unix_socket = interface.get('UNIX_SOCKET')
                if not listen and not unix_socket:
                    raise ValueError(
                        'Interface MUST listen either on TCP '
                        'or UNIX socket or both')
                host, port = parse_host(listen) if listen else (None, None)
                # Processes
                try:
                    processes = self.config_parser.getint(
                        interface_name, 'Processes')
                except CONFIGPARSER_EXC:
                    processes = int(interface.get('PROCESSES', 1))
                # Urls
                try:
                    urls_obj_name = self.config_parser.get(
                        interface_name, 'Urls')
                except CONFIGPARSER_EXC:
                    urls_obj_name = interface.get('URLS', '')
                if urls_obj_name:
                    urls = import_object(urls_obj_name)
                else:
                    urls = ()

                self._cached_values['interfaces'].append(
                    self.Interface(
                        name, host, port, unix_socket, processes, urls)
                )
        return self._cached_values['interfaces']
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
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)
63652
def virtual_interface_list(self, name):
        '''
        
        '''
        nt_ks = self.compute_conn
        nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
        return [network.__dict__ for network in nets]
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
486597
def _subnets(proto='inet', interfaces_=None):
    '''
    
    '''
    if interfaces_ is None:
        ifaces = interfaces()
    elif isinstance(interfaces_, list):
        ifaces = {}
        for key, value in six.iteritems(interfaces()):
            if key in interfaces_:
                ifaces[key] = value
    else:
        ifaces = {interfaces_: interfaces().get(interfaces_, {})}

    ret = set()

    if proto == 'inet':
        subnet = 'netmask'
        dflt_cidr = 32
    elif proto == 'inet6':
        subnet = 'prefixlen'
        dflt_cidr = 128
    else:
        log.error('Invalid proto %s calling subnets()', proto)
        return

    for ip_info in six.itervalues(ifaces):
        addrs = ip_info.get(proto, [])
        addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])

        for intf in addrs:
            if subnet in intf:
                intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet]))
            else:
                intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr))
            if not intf.is_loopback:
                ret.add(intf.network)
    return [six.text_type(net) for net in sorted(ret)]
45552
def get_working_if():
    """"""
    try:
        # return the interface associated with the route with smallest
        # mask (route by default if it exists)
        iface = min(conf.route.routes, key=lambda x: x[1])[3]
    except ValueError:
        # no route
        iface = scapy.consts.LOOPBACK_INTERFACE
    if iface.is_invalid():
        # Backup mode: try them all
        for iface in six.itervalues(IFACES):
            if not iface.is_invalid():
                return iface
        return None
    return iface
526659
def get_if_raw_addr(ifname):
    """"""  # noqa: E501

    # Get ifconfig output
    try:
        fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        warning("Failed to execute ifconfig: (%s)", msg)
        return b"\0\0\0\0"

    # Get IPv4 addresses
    addresses = [l for l in fd if l.find("inet ") >= 0]
    if not addresses:
        warning("No IPv4 address found on %s !", ifname)
        return b"\0\0\0\0"

    # Pack the first address
    address = addresses[0].split(' ')[1]
    if '/' in address:  # NetBSD 8.0
        address = address.split("/")[0]
    return socket.inet_pton(socket.AF_INET, address)
201517
def get_dns_servers(interface='Local Area Connection'):
    '''
    
    '''
    # remove any escape characters
    interface = interface.split('\\')
    interface = ''.join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapter(NetEnabled=True):
            if interface == iface.NetConnectionID:
                iface_config = c.Win32_NetworkAdapterConfiguration(Index=iface.Index).pop()
                try:
                    return list(iface_config.DNSServerSearchOrder)
                except TypeError:
                    return []
    log.debug('Interface "%s" not found', interface)
    return False
510654
def _interfaces_ip(out):
    
    ret = dict()

    def parse_network(value, cols):
        """
        Return a tuple of ip, netmask, broadcast
        based on the current set of cols
        """
        brd = None
        if '/' in value:  # we have a CIDR in this address
            ip, cidr = value.split('/')  # pylint: disable=C0103
        else:
            ip = value  # pylint: disable=C0103
            cidr = 32

        if type_ == 'inet':
            mask = cidr_to_ipv4_netmask(int(cidr))
            if 'brd' in cols:
                brd = cols[cols.index('brd') + 1]
        elif type_ == 'inet6':
            mask = cidr
        return (ip, mask, brd)

    groups = re.compile('\r?\n\\d').split(out)
    for group in groups:
        iface = None
        data = dict()

        for line in group.splitlines():
            if ' ' not in line:
                continue
            match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
            if match:
                iface, parent, attrs = match.groups()
                if 'UP' in attrs.split(','):
                    data['up'] = True
                else:
                    data['up'] = False
                if parent:
                    data['parent'] = parent
                continue

            cols = line.split()
            if len(cols) >= 2:
                type_, value = tuple(cols[0:2])
                iflabel = cols[-1:][0]
                if type_ in ('inet', 'inet6'):
                    if 'secondary' not in cols:
                        ipaddr, netmask, broadcast = parse_network(value, cols)
                        if type_ == 'inet':
                            if 'inet' not in data:
                                data['inet'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['netmask'] = netmask
                            addr_obj['broadcast'] = broadcast
                            addr_obj['label'] = iflabel
                            data['inet'].append(addr_obj)
                        elif type_ == 'inet6':
                            if 'inet6' not in data:
                                data['inet6'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['prefixlen'] = netmask
                            data['inet6'].append(addr_obj)
                    else:
                        if 'secondary' not in data:
                            data['secondary'] = list()
                        ip_, mask, brd = parse_network(value, cols)
                        data['secondary'].append({
                            'type': type_,
                            'address': ip_,
                            'netmask': mask,
                            'broadcast': brd,
                            'label': iflabel,
                        })
                        del ip_, mask, brd
                elif type_.startswith('link'):
                    data['hwaddr'] = value
        if iface:
            ret[iface] = data
            del iface, data
    return ret
279532
def _get_base_interface_info(interface):
    '''
    
    '''
    blacklist = {
        'tcpip': {
            'name': [],
            'type': [],
            'additional_protocol': False
        },
        'disabled': {
            'name': ['eth0'],
            'type': ['gadget'],
            'additional_protocol': False
        },
        'ethercat': {
            'name': ['eth0'],
            'type': ['gadget', 'usb', 'wlan'],
            'additional_protocol': True
        },
        '_': {
            'usb': 'sys',
            'gadget': 'uevent',
            'wlan': 'uevent'
        }
    }
    return {
        'label': interface.name,
        'connectionid': interface.name,
        'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist),
        'adapter_mode': _get_adapter_mode_info(interface.name),
        'up': interface.flags & IFF_RUNNING != 0,
        'ipv4': {
            'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'],
            'requestmode': _get_request_mode_info(interface.name)
        },
        'hwaddr': interface.hwaddr[:-1]
    }
993589
def cli(env, ip_address):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    addr_info = mgr.ip_lookup(ip_address)

    if not addr_info:
        raise exceptions.CLIAbort('Not found')

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', addr_info['id']])
    table.add_row(['ip', addr_info['ipAddress']])

    subnet_table = formatting.KeyValueTable(['name', 'value'])
    subnet_table.align['name'] = 'r'
    subnet_table.align['value'] = 'l'
    subnet_table.add_row(['id', addr_info['subnet']['id']])
    subnet_table.add_row(['identifier',
                          '%s/%s' % (addr_info['subnet']['networkIdentifier'],
                                     str(addr_info['subnet']['cidr']))])
    subnet_table.add_row(['netmask', addr_info['subnet']['netmask']])
    if addr_info['subnet'].get('gateway'):
        subnet_table.add_row(['gateway', addr_info['subnet']['gateway']])
    subnet_table.add_row(['type', addr_info['subnet'].get('subnetType')])

    table.add_row(['subnet', subnet_table])

    if addr_info.get('virtualGuest') or addr_info.get('hardware'):
        device_table = formatting.KeyValueTable(['name', 'value'])
        device_table.align['name'] = 'r'
        device_table.align['value'] = 'l'
        if addr_info.get('virtualGuest'):
            device = addr_info['virtualGuest']
            device_type = 'vs'
        else:
            device = addr_info['hardware']
            device_type = 'server'
        device_table.add_row(['id', device['id']])
        device_table.add_row(['name', device['fullyQualifiedDomainName']])
        device_table.add_row(['type', device_type])
        table.add_row(['device', device_table])
    env.fout(table)