Use Python's socket interface to lookup addresses
    :param name: Name of record to search
    :param rdtype: A or AAAA
    :param timeout: ignored
    :return: [] of addresses or False if error
330793
def _lookup_gai(name, rdtype, timeout=None):
    '''
    
    '''
    try:
        sock_t = {
            'A':    socket.AF_INET,
            'AAAA': socket.AF_INET6
        }[rdtype]
    except KeyError:
        raise ValueError('Invalid DNS type {} for gai lookup'.format(rdtype))

    if timeout:
        log.info('Ignoring timeout on gai resolver; fix resolv.conf to do that')

    try:
        addresses = [sock[4][0] for sock in socket.getaddrinfo(name, None, sock_t, 0, socket.SOCK_RAW)]
        return addresses
    except socket.gaierror:
        return False
805398
def query(self, base, filterstr, attrlist=None):
		
		return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
257902
public static InetAddress[]
    getAllByName(String name) throws UnknownHostException {
        try {
            InetAddress addr = getByAddress(name);
            return new InetAddress[]{addr};
        } catch (UnknownHostException e) {
            Record[] records = lookupHostName(name);
            InetAddress[] addrs = new InetAddress[records.length];
            for (int i = 0; i < records.length; i++)
                addrs[i] = addrFromRecord(name, records[i]);
            return addrs;
        }
    }
1173252
public static InetAddress
    getByName(String name) throws UnknownHostException {
        try {
            return getByAddress(name);
        } catch (UnknownHostException e) {
            Record[] records = lookupHostName(name);
            return addrFromRecord(name, records[0]);
        }
    }
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
1322829
def _lookup_dnspython(name, rdtype, timeout=None, servers=None, secure=None):
    '''
    
    '''
    resolver = dns.resolver.Resolver()

    if timeout is not None:
        resolver.lifetime = float(timeout)
    if servers:
        resolver.nameservers = servers
    if secure:
        resolver.ednsflags += dns.flags.DO

    try:
        res = [_data_clean(rr.to_text())
               for rr in resolver.query(name, rdtype, raise_on_no_answer=False)]
        return res
    except dns.rdatatype.UnknownRdatatype:
        raise ValueError('Invalid DNS type {}'.format(rdtype))
    except (dns.resolver.NXDOMAIN,
            dns.resolver.YXDOMAIN,
            dns.resolver.NoNameservers,
            dns.exception.Timeout):
        return False
938398
def lookup_domain(domain, nameservers=[], rtype="A",
                  exclude_nameservers=[], timeout=2):
    """"""
    dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype,
                       exclude_nameservers=exclude_nameservers, timeout=timeout)
    return dns_exp.lookup_domain(domain)
267651
def rpc_get_name_record(self, name, **con_info):
        
        res = None
        if check_name(name):
            res = self.get_name_record(name, include_expired=True, include_history=False)
        elif check_subdomain(name):
            res = self.get_subdomain_record(name, include_history=False)
        else:
            return {'error': 'Invalid name or subdomain', 'http_status': 400}

        if 'error' in res:
            return {'error': res['error'], 'http_status': 404}

        # also get a DID
        did_info = None
        did = None
        if check_name(name):
            did_info = self.get_name_DID_info(name)
        elif check_subdomain(name):
            did_info = self.get_subdomain_DID_info(name)
        else:
            return {'error': 'Invalid name or subdomain', 'http_status': 400}

        if did_info is not None:
            did = make_DID(did_info['name_type'], did_info['address'], did_info['index'])
            res['record']['did'] = did

        return self.success_response({'record': res['record']})
994220
def get_connection_by_name(self, name):
        ''''''
        with self._mutex:
            for conn in self.connections:
                if conn.name == name:
                    return conn
            return None
1216907
def lookupByName(self, name):
        
        res = yield queue.executeInThread(self.connection.lookupByName, name)
        return self.DomainClass(self, res)
958539
private LookupResult resolveAllAddressesForHostname(Object key) {

        try {
            List<ADnsAnswer> ip4Answers = new ArrayList<>();
            List<ADnsAnswer> ip6Answers = new ArrayList<>();

            // UnknownHostException is a valid case when the DNS record does not exist. Silently ignore and do not log an error.
            try {
                ip4Answers = dnsClient.resolveIPv4AddressForHostname(key.toString(), true); // Include IP version
            } catch (UnknownHostException e) {
            }

            try {
                ip6Answers = dnsClient.resolveIPv6AddressForHostname(key.toString(), true); // Include IP version
            } catch (UnknownHostException e) {
            }

            // Select answer for single value. Prefer use of IPv4 address. Only return IPv6 address if no IPv6 address found.
            final String singleValue;
            if (CollectionUtils.isNotEmpty(ip4Answers)) {
                singleValue = ip4Answers.get(0).ipAddress();
            } else if (CollectionUtils.isNotEmpty(ip6Answers)) {
                singleValue = ip6Answers.get(0).ipAddress();
            } else {
                LOG.debug("Could not resolve [A/AAAA] records hostname [{}].", key);
                return LookupResult.empty();
            }

            final LookupResult.Builder builder = LookupResult.builder();
            if (StringUtils.isNotBlank(singleValue)) {
                builder.single(singleValue);
            }

            final List<ADnsAnswer> allAnswers = new ArrayList<>();
            allAnswers.addAll(ip4Answers);
            allAnswers.addAll(ip6Answers);

            if (CollectionUtils.isNotEmpty(allAnswers)) {
                builder.multiValue(Collections.singletonMap(RESULTS_FIELD, allAnswers));
            }

            assignMinimumTTL(allAnswers, builder);

            return builder.build();
        } catch (Exception e) {
            LOG.error("Could not resolve [A/AAAA] records for hostname [{}]. Cause [{}]", key, ExceptionUtils.getRootCauseMessage(e));
            errorCounter.inc();
            return LookupResult.empty();
        }
    }
386425
def lookup!(nameserver=nil)
      resolver = Resolv.resolver(nameserver)
      hosts = begin
                resolver.getnames(self.address.to_s)
              rescue
                []
              end

      hosts.map! do |name|
        HostName.first_or_create(
          :address => name,
          :ip_addresses => [self]
        )
      end

      return hosts
    end
27460
def _list_records(self, rtype=None, name=None, content=None):
        
        if name:
            name = self._relative_name(name)
        if not rtype:
            rtype = "ANY"

        filter_query = {"rdtype": rtype, "name": name, "content": content}

        with localzone.manage(self.filename, self.origin, autosave=True) as zone:
            records = zone.find_record(**filter_query)  # pylint: disable=no-member

        result = []
        for record in records:
            rdict = {
                "type": record.rdtype,
                "name": self._full_name(record.name),
                "ttl": record.ttl,
                "content": record.content,
                "id": record.hashid,
            }

            if rdict["type"] == "TXT":
                rdict["content"] = rdict["content"].replace('"', "")

            result.append(rdict)

        LOGGER.debug("list_records: %s", result)
        return result
861373
def lookup_ring(timeout=5, &block)
      return lookup_ring_any(timeout) unless block_given?

      msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout])
      @broadcast_list.each do |it|
	soc = UDPSocket.open
	begin
	  soc.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
	  soc.send(msg, 0, it, @port)
	rescue
	  nil
	ensure
	  soc.close
	end
      end
      sleep(timeout)
    end
111641
def _lookup_drill(name, rdtype, timeout=None, servers=None, secure=None):
    '''
    
    '''
    cmd = 'drill '
    if secure:
        cmd += '-D -o ad '
    cmd += '{0} {1} '.format(rdtype, name)
    if servers:
        cmd += ''.join(['@{0} '.format(srv) for srv in servers])
    cmd = __salt__['cmd.run_all'](
        cmd, timeout=timeout,
        python_shell=False, output_loglevel='quiet')

    if cmd['retcode'] != 0:
        log.warning('drill returned (%s): %s', cmd['retcode'], cmd['stderr'])
        return False

    lookup_res = iter(cmd['stdout'].splitlines())
    validated = False
    res = []
    try:
        line = ''
        while 'ANSWER SECTION' not in line:
            line = next(lookup_res)
        while True:
            line = next(lookup_res)
            line = line.strip()
            if not line or line.startswith(';;'):
                break

            l_type, l_rec = line.split(None, 4)[-2:]
            if l_type == 'CNAME' and rdtype != 'CNAME':
                continue
            elif l_type == 'RRSIG':
                validated = True
                continue
            elif l_type != rdtype:
                raise ValueError('Invalid DNS type {}'.format(rdtype))

            res.append(_data_clean(l_rec))

    except StopIteration:
        pass

    if res and secure and not validated:
        return False
    else:
        return res
1213448
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None):
        
        records = []
        rrsets = zone.iterate_rdatasets() if zone else []
        for rname, rdataset in rrsets:
            rtype = dns.rdatatype.to_text(rdataset.rdtype)
            if ((not rdtype or rdtype == rtype)
                    and (not name or name == rname.to_text())):
                for rdata in rdataset:
                    rdata = rdata.to_text()
                    if not content or self._convert_content(rtype, content) == rdata:
                        raw_rdata = self._clean_TXT_record({'type': rtype,
                                                            'content': rdata})['content']
                        data = {
                            'type': rtype,
                            'name': rname.to_text(True),
                            'ttl': int(rdataset.ttl),
                            'content': raw_rdata,
                            'id': Provider._create_identifier(rtype, rname.to_text(), raw_rdata)
                        }
                        records.append(data)
        return records
1277449
def load(self, callback=None, errback=None, reload=False):
        
        if not reload and self.data:
            raise AddressException('Address already loaded')

        def success(result, *args):
            self.data = result
            self.id = result['id']
            self.prefix = result['prefix']
            self.type = result['type']
            self.network = Network(self.config, id=result['network_id'])
            # self.scope_group = Scopegroup(config=self.config, id=result['scope_group_id']) NYI
            if self.type != 'host':
                self.report = self._rest.report(self.id)
                children = self._rest.retrieve_children(self.id)
                self.children = [Address(self.config, id=child['id']) for child in
                                 children if len(children) > 0]
            try:
                parent = self._rest.retrieve_parent(self.id)
                self.parent = Address(self.config, id=parent['id'])
            except ResourceException:
                pass
            if callback:
                return callback(self)
            else:
                return self

        if self.id is None:
            if self.prefix is None or self.type is None or self.network is None:
                raise AddressException('Must at least specify an id or prefix, type and network')
            else:
                network_id = self.network.id
                try:
                    self.id = [address for address in self._rest.list() if address['prefix'] == self.prefix and address[
                        'type'] == self.type and address['network_id'] == network_id][0]['id']
                except IndexError:
                    raise AddressException("Could not find address by prefix. It may not exist, or is a child address. "
                                           "Use the topmost parent prefix or specify ID")

        return self._rest.retrieve(self.id, callback=success,
                                   errback=errback)