Return array of MAC addresses for a single VLAN from a single node at an IP
771363
def get_macs_for_vlan(self, ip, vlan, display_progress=0, snmpobj=None, system_name=None, ifname_vbtbl=None):
        '''
        
        '''
        ret_macs = []

        if (snmpobj == None):
            snmpobj = natlas_snmp(ip)
            if (snmpobj.get_cred(self.config.snmp_creds) == 0):
                return None
        if (ifname_vbtbl == None):
            ifname_vbtbl = snmpobj.get_bulk(OID_IFNAME)
        if (system_name == None):
            system_name = util.shorten_host_name(snmpobj.get_val(OID_SYSNAME), self.config.host_domains)

        # change our SNMP credentials
        old_cred = snmpobj.v2_community
        snmpobj.v2_community = old_cred + '@' + str(vlan)

        if (display_progress == 1):
            sys.stdout.write(str(vlan)) # found VLAN
            sys.stdout.flush()

        # get CAM table for this VLAN
        cam_vbtbl       = snmpobj.get_bulk(OID_VLAN_CAM)
        portnum_vbtbl   = snmpobj.get_bulk(OID_BRIDGE_PORTNUMS)
        ifindex_vbtbl   = snmpobj.get_bulk(OID_IFINDEX)
        cam_match       = None

        if (cam_vbtbl == None):
            # error getting CAM for VLAN
            return None

        for cam_row in cam_vbtbl:
            for cam_n, cam_v in cam_row:
                cam_entry = natlas_mac.mac_format_ascii(cam_v, 0)

                # find the interface index
                p               = cam_n.getOid()
                portnum_oid     = '%s.%i.%i.%i.%i.%i.%i' % (OID_BRIDGE_PORTNUMS, p[11], p[12], p[13], p[14], p[15], p[16])
                bridge_portnum  = snmpobj.cache_lookup(portnum_vbtbl, portnum_oid)

                # get the interface index and description
                try:
                    ifidx       = snmpobj.cache_lookup(ifindex_vbtbl, OID_IFINDEX + '.' + bridge_portnum)
                    port        = snmpobj.cache_lookup(ifname_vbtbl, OID_IFNAME + '.' + ifidx)
                except TypeError:
                    port = 'None'

                mac_addr = natlas_mac.mac_format_ascii(cam_v, 1)
                
                if (display_progress == 1):
                    sys.stdout.write('.') # found CAM entry
                    sys.stdout.flush()

                entry = natlas_mac.mac_object(system_name, ip, vlan, mac_addr, port)
                ret_macs.append(entry)

        # restore SNMP credentials
        snmpobj.v2_community = old_cred
        return ret_macs
1207149
def get_slave_addrs(mgr_addr, N):
    '''
    '''
    return  [(HOST, p) for p in range(mgr_addr+1, mgr_addr+1+N)]
342258
def _list_vlans_by_name(self, name):
        
        results = self.list_vlans(name=name, mask='id')
        return [result['id'] for result in results]
457872
def get_host_addresses(use_ipv4, use_ipv6):
    
    addresses = []
    for interface in netifaces.interfaces():
        ifaddresses = netifaces.ifaddresses(interface)
        for address in ifaddresses.get(socket.AF_INET, []):
            if use_ipv4 and address['addr'] != '127.0.0.1':
                addresses.append(address['addr'])
        for address in ifaddresses.get(socket.AF_INET6, []):
            if use_ipv6 and address['addr'] != '::1' and '%' not in address['addr']:
                addresses.append(address['addr'])
    return addresses
873888
function getOwnIpAddresses() {
    // enumerate interfaces
    var net = os.networkInterfaces();
    var addresses = Object.keys(net)
        // flatten the array structure
        .map(function (k) { return net[k]; })
        .reduce(function (prev, cur) { return prev.concat.apply(prev, cur); }, [])
        // only use external IPv4 ones
        .filter(function (add) { return !add.internal && add.family === "IPv4"; })
        // extract address as number array
        .map(function (k) { return k.address.split(".").map(function (num) { return +num; }); })
        // ignore unconnected ones
        .filter(function (add) { return add[0] !== 169; })
        // turn the address into a string again
        .map(function (a) { return a[0] + "." + a[1] + "." + a[2] + "." + a[3]; });
    return addresses;
}
516539
def switchport_pvlan_trunk_allowed_vlan
      return nil if switchport_mode == :disabled
      vlans = config_get('interface', 'switchport_pvlan_trunk_allowed_vlan',
                         name: @name)
      vlans = vlans.join(',') if vlans.is_a?(Array)
      vlans = Utils.normalize_range_array(vlans, :string) unless vlans == 'none'
      vlans
    end
559786
def ParseMultiple(self, result_dicts):
    """"""
    for result_dict in result_dicts:
      args = {"ifname": result_dict["Description"]}
      args["mac_address"] = binascii.unhexlify(
          result_dict["MACAddress"].replace(":", ""))

      self._ConvertIPs([("IPAddress", "addresses"),
                        ("DefaultIPGateway", "ip_gateway_list"),
                        ("DHCPServer", "dhcp_server_list")], result_dict, args)

      if "DHCPLeaseExpires" in result_dict:
        args["dhcp_lease_expires"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseExpires"])

      if "DHCPLeaseObtained" in result_dict:
        args["dhcp_lease_obtained"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseObtained"])

      yield rdf_client_network.Interface(**args)

      yield rdf_client_network.DNSClientConfiguration(
          dns_server=result_dict["DNSServerSearchOrder"],
          dns_suffix=result_dict["DNSDomainSuffixSearchOrder"])
29915
def Convert(self, metadata, interface, token=None):
    """"""
    ip4_addresses = []
    ip6_addresses = []
    for addr in interface.addresses:
      if addr.address_type == addr.Family.INET:
        ip4_addresses.append(addr.human_readable_address)
      elif addr.address_type == addr.Family.INET6:
        ip6_addresses.append(addr.human_readable_address)
      else:
        raise ValueError("Invalid address type: %s" % addr.address_type)

    result = ExportedNetworkInterface(
        metadata=metadata,
        ifname=interface.ifname,
        ip4_addresses=" ".join(ip4_addresses),
        ip6_addresses=" ".join(ip6_addresses))

    if interface.mac_address:
      result.mac_address = interface.mac_address.human_readable_address

    yield result
1350888
def mac_table(self):
        
        table = []
        namespace = 'urn:brocade.com:mgmt:brocade-mac-address-table'
        request_mac_table = ET.Element('get-mac-address-table',
                                       xmlns=namespace)
        result = self._callback(request_mac_table, handler='get')
        for entry in result.findall('{%s}mac-address-table' % namespace):
            address = entry.find('{%s}mac-address' % namespace).text
            vlan = entry.find('{%s}vlanid' % namespace).text
            mac_type = entry.find('{%s}mac-type' % namespace).text
            state = entry.find('{%s}mac-state' % namespace).text
            interface = entry.find('{%s}forwarding-interface' % namespace)
            interface_type = interface.find('{%s}interface-type' %
                                            namespace).text
            interface_name = interface.find('{%s}interface-name' %
                                            namespace).text
            interface = '%s%s' % (interface_type, interface_name)

            table.append(dict(mac_address=address, interface=interface,
                              state=state, vlan=vlan,
                              type=mac_type))

        return table
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
1169158
def GetIPAddresses(self):
    """"""
    result = []
    filtered_ips = ["127.0.0.1", "::1", "fe80::1"]

    for interface in self.interfaces:
      for address in interface.addresses:
        if address.human_readable_address not in filtered_ips:
          result.append(Text(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])
1234761
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))

  addresses = {}
  macs = {}
  ifs = set()

  m = p_ifa
  while m:
    ifname = ctypes.string_at(m.contents.ifa_name)
    ifs.add(ifname)
    try:
      iffamily = ord(m.contents.ifa_addr[0])

      if iffamily == 0x2:  # AF_INET
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrin))
        ip4 = bytes(list(data.contents.sin_addr))
        address_type = rdf_client_network.NetworkAddress.Family.INET
        address = rdf_client_network.NetworkAddress(
            address_type=address_type, packed_bytes=ip4)
        addresses.setdefault(ifname, []).append(address)

      if iffamily == 0x11:  # AF_PACKET
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrll))
        addlen = data.contents.sll_halen
        macs[ifname] = bytes(list(data.contents.sll_addr[:addlen]))

      if iffamily == 0xA:  # AF_INET6
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrin6))
        ip6 = bytes(list(data.contents.sin6_addr))
        address_type = rdf_client_network.NetworkAddress.Family.INET6
        address = rdf_client_network.NetworkAddress(
            address_type=address_type, packed_bytes=ip6)
        addresses.setdefault(ifname, []).append(address)
    except ValueError:
      # Some interfaces don't have a iffamily and will raise a null pointer
      # exception. We still want to send back the name.
      pass

    m = m.contents.ifa_next

  libc.freeifaddrs(p_ifa)

  for interface in ifs:
    mac = macs.setdefault(interface, b"")
    address_list = addresses.setdefault(interface, b"")
    args = {"ifname": interface}
    if mac:
      args["mac_address"] = mac
    if addresses:
      args["addresses"] = address_list
    yield rdf_client_network.Interface(**args)
826933
def get_macs(self, ip, display_progress):
        '''
        
        '''
        if (ip == '0.0.0.0'):
            return None

        ret_macs = []
        snmpobj = natlas_snmp(ip)

        # find valid credentials for this node
        if (snmpobj.get_cred(self.config.snmp_creds) == 0):
            return None

        system_name = util.shorten_host_name(snmpobj.get_val(OID_SYSNAME), self.config.host_domains)

        # cache some common MIB trees
        vlan_vbtbl      = snmpobj.get_bulk(OID_VLANS)
        ifname_vbtbl    = snmpobj.get_bulk(OID_IFNAME)

        for vlan_row in vlan_vbtbl:
            for vlan_n, vlan_v in vlan_row:
                # get VLAN ID from OID
                vlan = natlas_snmp.get_last_oid_token(vlan_n)
                if (vlan >= 1002):
                    continue
                vmacs = self.get_macs_for_vlan(ip, vlan, display_progress, snmpobj, system_name, ifname_vbtbl)
                if (vmacs != None):
                    ret_macs.extend(vmacs)

        if (display_progress == 1):
            print('')

        return ret_macs
939803
function getMyIPs() {
	var ips = [];
	var ifs = os.networkInterfaces();
	for (var i in ifs) {
		for (var j in ifs[i]) {
			ips.push(ifs[i][j].address);
		}
	}
	return ips;
}
1209336
function getAddress(loopback, opt_family) {
  var family = opt_family || 'IPv4';
  var addresses = [];

  var interfaces;
  if (loopback) {
    var lo = getLoInterface();
    interfaces = lo ? [lo] : null;
  }
  interfaces = interfaces || os.networkInterfaces();
  for (var key in interfaces) {
    interfaces[key].forEach(function(ipAddress) {
      if (ipAddress.family === family &&
          ipAddress.internal === loopback) {
        addresses.push(ipAddress.address);
      }
    });
  }
  return addresses[0];
}
838836
def getmacbyip(ip, chainCC=0):
    """"""
    if isinstance(ip, Net):
        ip = next(iter(ip))
    ip = inet_ntoa(inet_aton(ip or "0.0.0.0"))
    tmp = [orb(e) for e in inet_aton(ip)]
    if (tmp[0] & 0xf0) == 0xe0:  # mcast @
        return "01:00:5e:%.2x:%.2x:%.2x" % (tmp[1] & 0x7f, tmp[2], tmp[3])
    iff, _, gw = conf.route.route(ip)
    if ((iff == consts.LOOPBACK_INTERFACE) or (ip == conf.route.get_if_bcast(iff))):  # noqa: E501
        return "ff:ff:ff:ff:ff:ff"
    if gw != "0.0.0.0":
        ip = gw

    mac = conf.netcache.arp_cache.get(ip)
    if mac:
        return mac

    try:
        res = srp1(Ether(dst=ETHER_BROADCAST) / ARP(op="who-has", pdst=ip),
                   type=ETH_P_ARP,
                   iface=iff,
                   timeout=2,
                   verbose=0,
                   chainCC=chainCC,
                   nofilter=1)
    except Exception:
        return None
    if res is not None:
        mac = res.payload.hwsrc
        conf.netcache.arp_cache[ip] = mac
        return mac
    return None