Use nslookup to lookup addresses
    :param name: Name of record to search
    :param rdtype: DNS record type
    :param timeout: server response timeout
    :param server: server to query
    :return: [] of records or False if error
778917
def _lookup_nslookup(name, rdtype, timeout=None, server=None):
    '''
    
    '''
    cmd = 'nslookup -query={0} {1}'.format(rdtype, name)

    if timeout is not None:
        cmd += ' -timeout={0}'.format(int(timeout))
    if server is not None:
        cmd += ' {0}'.format(server)

    cmd = __salt__['cmd.run_all'](cmd, python_shell=False, output_loglevel='quiet')

    if cmd['retcode'] != 0:
        log.warning(
            'nslookup returned (%s): %s',
            cmd['retcode'],
            cmd['stdout'].splitlines()[-1].strip(string.whitespace + ';')
        )
        return False

    lookup_res = iter(cmd['stdout'].splitlines())
    res = []
    try:
        line = next(lookup_res)
        if 'unknown query type' in line:
            raise ValueError('Invalid DNS type {}'.format(rdtype))

        while True:
            if name in line:
                break
            line = next(lookup_res)

        while True:
            line = line.strip()
            if not line or line.startswith('*'):
                break
            elif rdtype != 'CNAME' and 'canonical name' in line:
                name = line.split()[-1][:-1]
                line = next(lookup_res)
                continue
            elif rdtype == 'SOA':
                line = line.split('=')
            elif line.startswith('Name:'):
                line = next(lookup_res)
                line = line.split(':', 1)
            elif line.startswith(name):
                if '=' in line:
                    line = line.split('=', 1)
                else:
                    line = line.split(' ')

            res.append(_data_clean(line[-1]))
            line = next(lookup_res)

    except StopIteration:
        pass

    if rdtype == 'SOA':
        return [' '.join(res[1:])]
    else:
        return res
405540
def _dns_info_mapper(self, raw_dns):
        """"""
        output = {}

        # Indentification
        output['identification'] = raw_dns['id']

        # Pull out all the flags
        flags = {}
        flags['type'] = 'query' if raw_dns['qr'] == 0 else 'response'
        flags['opcode'] = self.opcodes.get(raw_dns['opcode'], 'UNKNOWN')
        flags['authoritative'] = True if raw_dns['aa'] else False
        flags['truncated'] = True if raw_dns['tc'] else False
        flags['recursion_desired'] = True if raw_dns['rd'] else False
        flags['recursion_available'] = True if raw_dns['ra'] else False
        flags['zero'] = raw_dns['zero']
        flags['return_code'] = self.rcodes.get(raw_dns['rcode'], 'UNKNOWN')
        output['flags'] = flags

        # Question/Answer Counts
        counts = {}
        counts['questions'] = len(raw_dns['qd'])
        counts['answers'] = len(raw_dns['an'])
        counts['auth_answers'] = len(raw_dns['ns'])
        counts['add_answers'] = len(raw_dns['ar'])
        output['counts'] = counts

        # Queries/Questions
        queries = []
        for query in raw_dns['qd']:
            q = {'class': self.query_classes.get(query['cls'], 'UNKNOWN'),
                 'type': self.query_types.get(query['type'], 'UNKNOWN'),
                 'name': query['name'],
                 'data': query['data']}
            queries.append(q)
        output['queries'] = queries


        # Responses/Answers (Resource Record)
        output['answers'] = {}
        for section_name, section in zip(['answers', 'name_servers', 'additional'], ['an', 'ns', 'ar']):
            answers = []
            for answer in raw_dns[section]:
                ans_output = {}
                ans_output['name'] = answer['name']
                ans_output['type'] = self.query_types.get(answer['type'], 'UNKNOWN')
                ans_output['class'] = self.query_classes.get(answer['cls'], 'UNKNOWN')
                ans_output['ttl'] = answer['ttl']

                # Get the return data for this answer type
                rdata_field = self._get_rdata_field(answer)
                if rdata_field != 'unknown':
                    ans_output['rdata'] = answer[rdata_field]
                answers.append(ans_output)

            # Add data to this answer section
            output['answers'][section_name] = answers

        # Add any weird stuff
        weird = self._dns_weird(output)
        if weird:
            output['weird'] = weird

        return output
1216907
def lookupByName(self, name):
        
        res = yield queue.executeInThread(self.connection.lookupByName, name)
        return self.DomainClass(self, res)
130139
def lookup(self, ip_address):
        """"""

        # Is this already in our cache
        if self.ip_lookup_cache.get(ip_address):
            domain = self.ip_lookup_cache.get(ip_address)

        # Is the ip_address local or special
        elif not self.lookup_internal and net_utils.is_internal(ip_address):
            domain = 'internal'
        elif net_utils.is_special(ip_address):
            domain = net_utils.is_special(ip_address)

        # Look it up at this point
        else:
            domain = self._reverse_dns_lookup(ip_address)

        # Cache it
        self.ip_lookup_cache.set(ip_address, domain)

        # Return the domain
        return domain
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
1126345
def _list_records(self, rtype=None, name=None, content=None):
        
        opts = {'domain': self._domain}
        if rtype is not None:
            opts['type'] = rtype.upper()
        if name is not None:
            opts['name'] = self._full_name(name)
        if content is not None:
            opts['content'] = content
        opts.update(self._auth)

        response = self._api.nameserver.info(opts)
        self._validate_response(
            response=response, message='Failed to get records')

        records = []
        if 'record' in response['resData']:
            for record in response['resData']['record']:
                processed_record = {
                    'type': record['type'],
                    'name': record['name'],
                    'ttl': record['ttl'],
                    'content': record['content'],
                    'id': record['id']
                }
                records.append(processed_record)

        return records
1165647
def search(query, count=10)
      return [] if query.length < 4
      response = @connection.get DOMESTIC_URL, params: { q: query.to_ascii, count: count }
      addresses = response.parsed['addresses'].each do |a|
        a['address_id'] = Integer(a['address_id'])
        a['dpid'] = Integer(a['dpid']) if a['dpid']
      end
      addresses.map {|address| OpenStruct.new(address)}
    end
295700
def GET_name_info( self, path_info, name ):
        
        if not check_name(name) and not check_subdomain(name):
            return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)

        blockstackd_url = get_blockstackd_url()

        name_rec = None
        try:
            name_rec = blockstackd_client.get_name_record(name, include_history=False, hostport=blockstackd_url)
        except ValueError:
            return self._reply_json({'error': 'Invalid argument: not a well-formed name or subdomain'}, status_code=400)

        if 'error' in name_rec:
            if 'not found' in name_rec['error'].lower():
                return self._reply_json({'status': 'available'}, status_code=404)

            elif 'failed to load subdomain' in name_rec['error'].lower():

                # try to redirect to resolver, if given
                _, _, domain_name = blockstackd_scripts.is_address_subdomain(name)
                domain_rec = blockstackd_client.get_name_record(domain_name, include_history=False, hostport=blockstackd_url)

                if 'error' in domain_rec:
                    # no resolver known for on-chain name
                    return self._reply_json({'status': 'available', 'more': 'failed to look up parent domain'}, status_code=404)

                resolver_target = domain_rec.get('resolver', None)
                if resolver_target is None:
                    # no _resolver
                    return self._reply_json({'status': 'available',  'more': 'failed to find parent domain\'s resolver'}, status_code=404)

                redirect_location = resolver_target + '/v1/names/' + name
                log.debug("Redirect lookup on {} to {}".format(name, redirect_location))

                self._send_headers(status_code=301, more_headers={ 'Location': redirect_location })
                return self.wfile.write(json.dumps({'status': 'redirect'}))

            elif 'expired' in name_rec['error'].lower():
                return self._reply_json({'error': name_rec['error']}, status_code=404)

            else:
                return self._reply_json({'error': 'Blockstack daemon error: {}'.format(name_rec['error'])}, status_code=name_rec.get('http_status', 502))


        zonefile_txt = None

        if 'zonefile' in name_rec:
            zonefile_txt = base64.b64decode(name_rec['zonefile'])

        ret = {}

        if blockstackd_scripts.is_subdomain(name):
            # subdomain
            address = name_rec['address']
            if address:
                address = virtualchain.address_reencode(str(address))

            log.debug("{} is registered_subdomain".format(name))
            ret = {
                'status': 'registered_subdomain',
                'zonefile': zonefile_txt,
                'zonefile_hash': name_rec['value_hash'],
                'address': name_rec['address'],
                'blockchain': 'bitcoin',
                'last_txid': name_rec['txid'],
                'did': name_rec.get('did', {'error': 'Not supported for this name'})
            }

        else:
            status = 'revoked' if name_rec['revoked'] else 'registered'
            address = name_rec['address']
            if address:
                address = virtualchain.address_reencode(str(address))

            log.debug("{} is {}".format(name, status))
            ret = {
                'status': status,
                'zonefile': zonefile_txt,
                'zonefile_hash': name_rec['value_hash'],
                'address': address,
                'last_txid': name_rec['txid'],
                'blockchain': 'bitcoin',
                'expire_block': name_rec['expire_block'],      # expire_block is what blockstack.js expects
                'renewal_deadline': name_rec['renewal_deadline'],
                'grace_period': name_rec.get('grace_period', False),
                'resolver': name_rec.get('resolver', None),
                'did': name_rec.get('did', {'error': 'Not supported for this name'})
            }

        return self._reply_json(ret)
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
935465
def _get_record(self, name):
        """"""
        request = self._session.get(self._baseurl, params={'name': name,
                                                           'type': 'A'})
        if not request.ok:
            raise RuntimeError('Failed to search record: %s - %s' %
                               (self._format_hostname(name), request.json()))
        records = request.json()
        if len(records) == 0:
            return
        record = records[0]
        if 'record' not in record or 'id' not in record['record']:
            raise RuntimeError('Invalid record JSON format: %s - %s' %
                               (self._format_hostname(name), request.json()))
        return int(record['record']['id'])
803837
def _lookup_dig(name, rdtype, timeout=None, servers=None, secure=None):
    '''
    
    '''
    cmd = 'dig {0} -t {1} '.format(DIG_OPTIONS, rdtype)
    if servers:
        cmd += ''.join(['@{0} '.format(srv) for srv in servers])
    if timeout is not None:
        if servers:
            timeout = int(float(timeout) / len(servers))
        else:
            timeout = int(timeout)
        cmd += '+time={0} '.format(timeout)
    if secure:
        cmd += '+dnssec +adflag '

    cmd = __salt__['cmd.run_all']('{0} {1}'.format(cmd, name), python_shell=False, output_loglevel='quiet')

    if 'ignoring invalid type' in cmd['stderr']:
        raise ValueError('Invalid DNS type {}'.format(rdtype))
    elif cmd['retcode'] != 0:
        log.warning(
            'dig returned (%s): %s',
            cmd['retcode'], cmd['stderr'].strip(string.whitespace + ';')
        )
        return False
    elif not cmd['stdout']:
        return []

    validated = False
    res = []
    for line in cmd['stdout'].splitlines():
        _, rtype, rdata = line.split(None, 2)
        if rtype == 'CNAME' and rdtype != 'CNAME':
            continue
        elif rtype == 'RRSIG':
            validated = True
            continue
        res.append(_data_clean(rdata))

    if res and secure and not validated:
        return False
    else:
        return res
140275
def lookup_dn(cn)
      service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn
    end
422938
def lookup(item)
			# if item is an array, use it, otherwise make it one
			items = item
			if item.is_a? String
				items = [item]
			end
			# place the results in the results array
			results = []
			# for each ip or hostname
			items.each do |item|
				# sent is used to determine when we have all the answers
				sent = 0
				# record the start time
				@starttime = Time.now.to_f
				# determine the type of query
				itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain'
				# for each dnsbl that supports our type, create the DNS query packet and send it
				# rotate across our configured name servers and increment sent
				@dnsbls.each do |name,config|
					next if config['disabled']
					next unless config['type'] == itemtype
					begin
						msg = _encode_query(item,itemtype,config['domain'],config['apikey'])
						@sockets[@socket_index].send(msg,0)
						@socket_index += 1
						@socket_index %= @sockets.length
						sent += 1
					rescue Exception => e
						puts e
						puts e.backtrace.join("\n")
					end
				end
				# while we still expect answers
				while sent > 0
					# wait on the socket for maximally 1.5 seconds
					r,_,_ = IO.select(@sockets,nil,nil,1.5)
					# if we time out, break out of the loop
					break unless r
					# for each reply, decode it and receive results, decrement the pending answers
					r.each do |s|
						begin
							response = _decode_response(s.recv(4096))
							results += response
						rescue Exception => e
							puts e
							puts e.backtrace.join("\n")
						end
						sent -= 1
					end
				end
			end
			results
		end
1104839
def _get_matching_dns_entry_ids(self, identifier=None, rtype=None,
                                    name=None, content=None):
        """"""
        record_ids = []
        if not identifier:
            records = self._list_records(rtype, name, content)
            record_ids = [record['id'] for record in records]
        else:
            record_ids.append(identifier)
        return record_ids
322970
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
    '''
    
    '''
    data = {}
    if name:
        data['name'] = name
    if ipv4addr:
        data['ipv4addr'] = ipv4addr
    r = get_object('record:a', data=data, **api_opts)
    if r and len(r) > 1 and not allow_array:
        raise Exception('More than one result, use allow_array to return the data')
    return r
501698
def cmd_dns_lookup_forward(hostname, verbose):
    
    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        print("Looking up %s..." % hostname, file=sys.stderr)

    answer = lookup_forward(hostname)

    print(json.dumps(answer, indent=4))

    return True
786757
def _list_records(self, rtype=None, name=None, content=None):
        """"""
        records = []
        paginator = RecordSetPaginator(self.r53_client, self.domain_id)
        for record in paginator.all_record_sets():
            if rtype is not None and record['Type'] != rtype:
                continue
            if name is not None and record['Name'] != self._fqdn_name(name):
                continue
            if record.get('AliasTarget', None) is not None:
                record_content = [record['AliasTarget'].get('DNSName', None)]
            if record.get('ResourceRecords', None) is not None:
                record_content = [self._format_content(record['Type'], value['Value']) for value
                                  in record['ResourceRecords']]
            if content is not None and content not in record_content:
                continue
            LOGGER.debug('record: %s', record)
            records.append({
                'type': record['Type'],
                'name': self._full_name(record['Name']),
                'ttl': record.get('TTL', None),
                'content': record_content[0] if len(record_content) == 1 else record_content,
            })
        LOGGER.debug('list_records: %s', records)
        return records