Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
    network interface
480540
def _get_veths(net_data):
    '''
    
    '''
    if isinstance(net_data, dict):
        net_data = list(net_data.items())
    nics = salt.utils.odict.OrderedDict()
    current_nic = salt.utils.odict.OrderedDict()
    no_names = True
    for item in net_data:
        if item and isinstance(item, dict):
            item = list(item.items())[0]
        # skip LXC configuration comment lines, and play only with tuples conf
        elif isinstance(item, six.string_types):
            # deal with reflection of commented lxc configs
            sitem = item.strip()
            if sitem.startswith('#') or not sitem:
                continue
            elif '=' in item:
                item = tuple([a.strip() for a in item.split('=', 1)])
        if item[0] == 'lxc.network.type':
            current_nic = salt.utils.odict.OrderedDict()
        if item[0] == 'lxc.network.name':
            no_names = False
            nics[item[1].strip()] = current_nic
        current_nic[item[0].strip()] = item[1].strip()
    # if not ethernet card name has been collected, assuming we collected
    # data for eth0
    if no_names and current_nic:
        nics[DEFAULT_NIC] = current_nic
    return nics
541034
def get_router_diagnostics(self, x, y):
        
        # Read the block of memory
        data = self.read(0xe1000300, 64, x=x, y=y)

        # Convert to 16 ints, then process that as the appropriate tuple type
        return RouterDiagnostics(*struct.unpack("<16I", data))
145221
def nic_2_json(self):
        
        LOGGER.debug("NIC.nic_2_json")
        json_obj = {
            'nicID': self.id,
            'nicName': self.name,
            'nicMacAddress': self.mac_address,
            'nicDuplex': self.duplex,
            'nicSpeed': self.speed,
            'nicMtu': self.mtu,
            'nicOSInstanceID': self.nic_osi_id,
            'nicIPAddressID': self.nic_ipa_id
        }
        return json.dumps(json_obj)
1326202
def _parse_subnet(self, subnet_dict):
        
        if not subnet_dict:
            return
        alloc_pool = subnet_dict.get('allocation_pools')
        cidr = subnet_dict.get('cidr')
        subnet = cidr.split('/')[0]
        start = alloc_pool[0].get('start')
        end = alloc_pool[0].get('end')
        gateway = subnet_dict.get('gateway_ip')
        sec_gateway = subnet_dict.get('secondary_gw')
        return {'subnet': subnet, 'start': start, 'end': end,
                'gateway': gateway, 'sec_gateway': sec_gateway}
99654
def get_internal_ip():
    """"""
    nics = {}
    for interface_name in interfaces():
        addresses = ifaddresses(interface_name)
        try:
            nics[interface_name] = {
                'ipv4': addresses[AF_INET],
                'link_layer': addresses[AF_LINK],
                'ipv6': addresses[AF_INET6],
            }
        except KeyError:
            pass

    return nics
974171
function parseLinesWindowsNics(sections) {
  let nics = [];
  for (let i in sections) {
    if (sections.hasOwnProperty(i)) {
      if (sections[i].trim() !== '') {

        let lines = sections[i].trim().split('\r\n');
        let netEnabled = util.getValue(lines, 'NetEnabled', '=');
        if (netEnabled) {
          const speed = parseInt(util.getValue(lines, 'speed', '=').trim(), 10) / 1000000;
          nics.push({
            mac: util.getValue(lines, 'MACAddress', '=').toLowerCase(),
            name: util.getValue(lines, 'Name', '=').replace(/\]/g, ')').replace(/\[/g, '('),
            netEnabled: netEnabled === 'TRUE',
            speed: isNaN(speed) ? -1 : speed,
            operstate: util.getValue(lines, 'NetConnectionStatus', '=') === '2' ? 'up' : 'down',
            type: util.getValue(lines, 'AdapterTypeID', '=') === '9' ? 'wireless' : 'wired'
          });
        }
      }
    }
  }
  return nics;
}
519487
def _connect_lxd(spec):
    
    return {
        'method': 'lxd',
        'kwargs': {
            'container': spec.remote_addr(),
            'python_path': spec.python_path(),
            'lxc_path': spec.mitogen_lxc_path(),
            'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),
            'remote_name': get_remote_name(spec),
        }
    }
336527
def in6_getifaddr():
    

    # List all network interfaces
    if OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else:  # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    return ret
586233
def _parse_linux_cx_state(self, lines, tcp_states, state_col, protocol=None, ip_version=None):
        
        metrics = {}
        for _, val in iteritems(self.cx_state_gauge):
            metrics[val] = 0
        for l in lines:
            cols = l.split()
            if cols[0].startswith('tcp') or protocol == 'tcp':
                proto = "tcp{0}".format(ip_version) if ip_version else ("tcp4", "tcp6")[cols[0] == "tcp6"]
                if cols[state_col] in tcp_states:
                    metric = self.cx_state_gauge[proto, tcp_states[cols[state_col]]]
                    metrics[metric] += 1
            elif cols[0].startswith('udp') or protocol == 'udp':
                proto = "udp{0}".format(ip_version) if ip_version else ("udp4", "udp6")[cols[0] == "udp6"]
                metric = self.cx_state_gauge[proto, 'connections']
                metrics[metric] += 1

        return metrics
622879
def to_dict(self, prefix=None):
        '''
        
        '''

        conf_obj = dict(self)
        return self.__dictify__(conf_obj, prefix)
644518
def _parse_interfaces(self):
        
        interfaces = dict()
        names = re.findall(r'^interface (Po.+)$', self.config, re.M)
        for name in names:
            config = self.get_block('interface %s' % name)
            match = re.search(r'mlag (\d+)', config)
            if match:
                interfaces[name] = dict(mlag_id=match.group(1))
        return dict(interfaces=interfaces)
913929
def list_nictags(include_etherstubs=True):
    '''
    
    '''
    ret = {}
    cmd = 'nictagadm list -d "|" -p{0}'.format(
        ' -L' if not include_etherstubs else ''
    )
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'
    else:
        header = ['name', 'macaddress', 'link', 'type']
        for nictag in res['stdout'].splitlines():
            nictag = nictag.split('|')
            nictag_data = {}
            for field in header:
                nictag_data[field] = nictag[header.index(field)]
            ret[nictag_data['name']] = nictag_data
            del ret[nictag_data['name']]['name']
    return ret
368009
def _parse_connection_string(connstr):
    
    res = {}
    for item in connstr.split(';'):
        item = item.strip()
        if not item:
            continue
        key, value = item.split('=', 1)
        key = key.strip().lower().replace(' ', '_')
        value = value.strip()
        res[key] = value
    return res
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)]
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)
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')
858188
def parse_resolv(src='/etc/resolv.conf'):
    '''
    
    '''

    nameservers = []
    ip4_nameservers = []
    ip6_nameservers = []
    search = []
    sortlist = []
    domain = ''
    options = []

    try:
        with salt.utils.files.fopen(src) as src_file:
            # pylint: disable=too-many-nested-blocks
            for line in src_file:
                line = salt.utils.stringutils.to_unicode(line).strip().split()

                try:
                    (directive, arg) = (line[0].lower(), line[1:])
                    # Drop everything after # or ; (comments)
                    arg = list(itertools.takewhile(lambda x: x[0] not in ('#', ';'), arg))
                    if directive == 'nameserver':
                        addr = arg[0]
                        try:
                            ip_addr = ipaddress.ip_address(addr)
                            version = ip_addr.version
                            ip_addr = str(ip_addr)
                            if ip_addr not in nameservers:
                                nameservers.append(ip_addr)
                            if version == 4 and ip_addr not in ip4_nameservers:
                                ip4_nameservers.append(ip_addr)
                            elif version == 6 and ip_addr not in ip6_nameservers:
                                ip6_nameservers.append(ip_addr)
                        except ValueError as exc:
                            log.error('%s: %s', src, exc)
                    elif directive == 'domain':
                        domain = arg[0]
                    elif directive == 'search':
                        search = arg
                    elif directive == 'sortlist':
                        # A sortlist is specified by IP address netmask pairs.
                        # The netmask is optional and defaults to the natural
                        # netmask of the net. The IP address and optional
                        # network pairs are separated by slashes.
                        for ip_raw in arg:
                            try:
                                ip_net = ipaddress.ip_network(ip_raw)
                            except ValueError as exc:
                                log.error('%s: %s', src, exc)
                            else:
                                if '/' not in ip_raw:
                                    # No netmask has been provided, guess
                                    # the "natural" one
                                    if ip_net.version == 4:
                                        ip_addr = six.text_type(ip_net.network_address)
                                        # pylint: disable=protected-access
                                        mask = salt.utils.network.natural_ipv4_netmask(ip_addr)
                                        ip_net = ipaddress.ip_network(
                                            '{0}{1}'.format(ip_addr, mask),
                                            strict=False
                                        )
                                    if ip_net.version == 6:
                                        # TODO
                                        pass

                                if ip_net not in sortlist:
                                    sortlist.append(ip_net)
                    elif directive == 'options':
                        # Options allows certain internal resolver variables to
                        # be modified.
                        if arg[0] not in options:
                            options.append(arg[0])
                except IndexError:
                    continue

        if domain and search:
            # The domain and search keywords are mutually exclusive.  If more
            # than one instance of these keywords is present, the last instance
            # will override.
            log.debug(
                '%s: The domain and search keywords are mutually exclusive.',
                src
            )

        return {
            'nameservers':     nameservers,
            'ip4_nameservers': ip4_nameservers,
            'ip6_nameservers': ip6_nameservers,
            'sortlist':        [ip.with_netmask for ip in sortlist],
            'domain':          domain,
            'search':          search,
            'options':         options
        }
    except IOError:
        return {}