应答里有几条 A 记录

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

下面这段应答里,有几条 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\nwww.a.com 300 A 1.1.1.1\nwww.a.com 300 AAAA ::1\nmail.a.com 300 A 1.1.1.2\n"
print(count_type(text, "A"))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论