Provide a dict of the connected interfaces and their
    hw addresses (Mac Address)
483191
def hwaddr_interfaces():
    '''
    
    '''
    # Provides:
    #   hwaddr_interfaces
    ret = {}
    ifaces = _get_interfaces()
    for face in ifaces:
        if 'hwaddr' in ifaces[face]:
            ret[face] = ifaces[face]['hwaddr']
    return {'hwaddr_interfaces': ret}
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
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
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)
784971
def get_interfaces(self):
        """"""
        result = {}

        interfaces = junos_views.junos_iface_table(self.device)
        interfaces.get()
        interfaces_logical = junos_views.junos_logical_iface_table(self.device)
        interfaces_logical.get()

        # convert all the tuples to our pre-defined dict structure
        def _convert_to_dict(interfaces):
            # calling .items() here wont work.
            # The dictionary values will end up being tuples instead of dictionaries
            interfaces = dict(interfaces)
            for iface, iface_data in interfaces.items():
                result[iface] = {
                    "is_up": iface_data["is_up"],
                    # For physical interfaces <admin-status> will always be there, so just
                    # return the value interfaces[iface]['is_enabled']
                    # For logical interfaces if <iff-down> is present interface is disabled,
                    # otherwise interface is enabled
                    "is_enabled": (
                        True
                        if iface_data["is_enabled"] is None
                        else iface_data["is_enabled"]
                    ),
                    "description": (iface_data["description"] or ""),
                    "last_flapped": float((iface_data["last_flapped"] or -1)),
                    "mac_address": napalm.base.helpers.convert(
                        napalm.base.helpers.mac,
                        iface_data["mac_address"],
                        py23_compat.text_type(iface_data["mac_address"]),
                    ),
                    "speed": -1,
                    "mtu": 0,
                }
                # result[iface]['last_flapped'] = float(result[iface]['last_flapped'])

                match_mtu = re.search(r"(\w+)", str(iface_data["mtu"]) or "")
                mtu = napalm.base.helpers.convert(int, match_mtu.group(0), 0)
                result[iface]["mtu"] = mtu
                match = re.search(r"(\d+|[Aa]uto)(\w*)", iface_data["speed"] or "")
                if match and match.group(1).lower() == "auto":
                    match = re.search(
                        r"(\d+)(\w*)", iface_data["negotiated_speed"] or ""
                    )
                if match is None:
                    continue
                speed_value = napalm.base.helpers.convert(int, match.group(1), -1)
                if speed_value == -1:
                    continue
                speed_unit = match.group(2)
                if speed_unit.lower() == "gbps":
                    speed_value *= 1000
                result[iface]["speed"] = speed_value

            return result

        result = _convert_to_dict(interfaces)
        result.update(_convert_to_dict(interfaces_logical))
        return result
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]
38414
def get_interface(iface):
    '''
    
    '''
    _interfaces = get_interfaces_details()
    for _interface in _interfaces['interfaces']:
        if _interface['connectionid'] == iface:
            return _dict_to_string(_interface)
    return None
1141577
def todict(self):
        '''
        
        '''
        return {
            'Source port': self.srcport,
            'Destination port': self.destport,
            'Protocol': self.protocol,
            'Destination address': self.destaddr}
897095
def ip_interfaces():
    '''
    
    '''
    # Provides:
    #   ip_interfaces

    if salt.utils.platform.is_proxy():
        return {}

    ret = {}
    ifaces = _get_interfaces()
    for face in ifaces:
        iface_ips = []
        for inet in ifaces[face].get('inet', []):
            if 'address' in inet:
                iface_ips.append(inet['address'])
        for inet in ifaces[face].get('inet6', []):
            if 'address' in inet:
                iface_ips.append(inet['address'])
        for secondary in ifaces[face].get('secondary', []):
            if 'address' in secondary:
                iface_ips.append(secondary['address'])
        ret[face] = iface_ips
    return {'ip_interfaces': ret}
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)
1111645
def get_mac(self):
        '''  '''
        ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14)
        res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
        address = struct.unpack('16sH14s', res)[2]
        mac = struct.unpack('6B8x', address)

        return ":".join(['%02X' % i for i in mac])
739656
def EnumerateInterfacesFromClient(args):
  """"""
  del args  # Unused

  libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
  ifa = Ifaddrs()
  p_ifa = ctypes.pointer(ifa)
  libc.getifaddrs(ctypes.pointer(p_ifa))

  for iface in ParseIfaddrs(p_ifa):
    yield iface

  libc.freeifaddrs(p_ifa)
662141
def get_interfaces_ip(self):
        """"""
        interfaces_ip = {}

        interface_table = junos_views.junos_ip_interfaces_table(self.device)
        interface_table.get()
        interface_table_items = interface_table.items()

        _FAMILY_VMAP_ = {
            "inet": "ipv4",
            "inet6": "ipv6"
            # can add more mappings
        }
        _FAMILY_MAX_PREFIXLEN = {"inet": 32, "inet6": 128}

        for interface_details in interface_table_items:
            ip_network = interface_details[0]
            ip_address = ip_network.split("/")[0]
            address = napalm.base.helpers.convert(
                napalm.base.helpers.ip, ip_address, ip_address
            )
            try:
                interface_details_dict = dict(interface_details[1])
                family_raw = interface_details_dict.get("family")
                interface = py23_compat.text_type(
                    interface_details_dict.get("interface")
                )
            except ValueError:
                continue
            prefix = napalm.base.helpers.convert(
                int, ip_network.split("/")[-1], _FAMILY_MAX_PREFIXLEN.get(family_raw)
            )
            family = _FAMILY_VMAP_.get(family_raw)
            if not family or not interface:
                continue
            if interface not in interfaces_ip.keys():
                interfaces_ip[interface] = {}
            if family not in interfaces_ip[interface].keys():
                interfaces_ip[interface][family] = {}
            if address not in interfaces_ip[interface][family].keys():
                interfaces_ip[interface][family][address] = {}
            interfaces_ip[interface][family][address]["prefix_length"] = prefix

        return interfaces_ip
1182249
def GetInterfaceDescription(self, interface):
        """"""
        try:
            i = self.interfaces[interface]
        except KeyError:
            raise InterfaceNotFound(interface)

        return {'description': i.description}
1262789
def win_interfaces():
    '''
    
    '''
    with salt.utils.winapi.Com():
        c = wmi.WMI()
        ifaces = {}
        for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
            ifaces[iface.Description] = dict()
            if iface.MACAddress:
                ifaces[iface.Description]['hwaddr'] = iface.MACAddress
            if iface.IPEnabled:
                ifaces[iface.Description]['up'] = True
                for ip in iface.IPAddress:
                    if '.' in ip:
                        if 'inet' not in ifaces[iface.Description]:
                            ifaces[iface.Description]['inet'] = []
                        item = {'address': ip,
                                'label': iface.Description}
                        if iface.DefaultIPGateway:
                            broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '')
                            if broadcast:
                                item['broadcast'] = broadcast
                        if iface.IPSubnet:
                            netmask = next((i for i in iface.IPSubnet if '.' in i), '')
                            if netmask:
                                item['netmask'] = netmask
                        ifaces[iface.Description]['inet'].append(item)
                    if ':' in ip:
                        if 'inet6' not in ifaces[iface.Description]:
                            ifaces[iface.Description]['inet6'] = []
                        item = {'address': ip}
                        if iface.DefaultIPGateway:
                            broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '')
                            if broadcast:
                                item['broadcast'] = broadcast
                        if iface.IPSubnet:
                            netmask = next((i for i in iface.IPSubnet if ':' in i), '')
                            if netmask:
                                item['netmask'] = netmask
                        ifaces[iface.Description]['inet6'].append(item)
            else:
                ifaces[iface.Description]['up'] = False
    return ifaces
855842
def get_interface_addresses():
    

    addresses = []
    ifaces = netifaces.interfaces()
    for iface in ifaces:
        addrs = netifaces.ifaddresses(iface)
        families = addrs.keys()

        # put IPv4 to the end so it lists as the main iface address
        if netifaces.AF_INET in families:
            families.remove(netifaces.AF_INET)
            families.append(netifaces.AF_INET)

        for family in families:
            for addr in addrs[family]:
                address = {
                    'name': iface,
                    'family': family,
                    'ip': addr['addr'],
                }
                addresses.append(address)

    return addresses
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