应答里第一个地址
下面这段应答里,第一条 A 记录的地址是多少?
用 dig 查一个域名会打出一段应答,本节把它的 answer 段整理成每行「名字 TTL 类型 值」(; 开头是注释)。answers(文本) 解析成(名字,TTL,类型,值)的列表,count_type 数某类型几条,first_ip 取第一条 A 记录的地址,ttl_of 取某名字的 TTL。
def answers(text):
# 解析一段应答文本,每行「name ttl type value」,交回 (name,ttl,type,value) 列表
out = []
for line in text.strip().splitlines():
line = line.strip()
if not line or line.startswith(";"): # ; 开头是注释行
continue
name, ttl, typ, value = line.split()
out.append((name, int(ttl), typ, value))
return out
def count_type(text, typ):
return sum(1 for a in answers(text) if a[2] == typ)
def first_ip(text):
# 应答里第一条 A 记录的地址
for name, ttl, typ, value in answers(text):
if typ == "A":
return value
return "无"
def ttl_of(text, name):
for n, ttl, typ, value in answers(text):
if n == name:
return ttl
return -1
text = "; ans\nshop.com 60 CNAME www.shop.com\nwww.shop.com 60 A 10.0.0.9\n"
print(first_ip(text))
全部评论