在 dnspython 中返回 'A' DNS 记录

returning 'A' DNS record in dnspython

我正在使用 dnspython 获取 'A' 记录和 return 结果(给定域的 IP 地址)。

我有这个简单的测试 python 脚本:

import dns.resolver

def resolveDNS():
    domain = "google.com" 
    resolver = dns.resolver.Resolver(); 
    answer = resolver.query(domain , "A")
    return answer

resultDNS = resolveDNS()
print resultDNS

然而,输出是:

<dns.resolver.Answer object at 0x0000000004F56C50>

我需要获取字符串形式的结果。如果是字符串数组,如何return呢?

您得到的答案实际上是 'A' 条记录的迭代器,因此您需要遍历这些记录:

answers = resolver.query(domain, 'A')
for answer in answers:
    print (answer.to_text())
import dns.resolver

def resolveDNS():
    domain = "google.com" 
    resolver = dns.resolver.Resolver(); 
    answer = resolver.query(domain , "A")
    return answer

resultDNS = resolveDNS()
answer = ''

for item in resultDNS:
    resultant_str = ','.join([str(item), answer])

print resultant_str

所以现在 resultant_str 是一个字符串类型的变量,它保存由逗号分隔的 A 记录。