diff --git a/main.py b/main.py index f34ccf2..9303b6e 100644 --- a/main.py +++ b/main.py @@ -237,29 +237,42 @@ def build_dns_query(domain): # 解析 DNS 响应报文 def parse_dns_response(response): - # 解析DNS响应报文,提取IP地址 + """ + 解析DNS响应报文,提取IP地址。 + + Args: + response: response -- DNS响应报文(字节流) + + Returns: + String: IP地址字符串,如果未找到A记录则返回None。 + """ + # 解析DNS响应报文的头部信息 # 响应头部:包含事务ID、标志、问题数、答案数等 transaction_id, flags, questions, answer_rrs, authority_rrs, additional_rrs = struct.unpack('>HHHHHH', response[:12]) - - # 跳过问题部分 + + # 初始化偏移量以解析响应报文的其余部分 offset = 12 + # 跳过问题部分,找到第一个答案记录的起始位置 while response[offset] != 0: length = response[offset] offset += length + 1 offset += 5 # 跳过结束符和查询类型、查询类部分 - - # 解析回答部分 + + # 解析回答部分,寻找A记录 # 答案数量 for _ in range(answer_rrs): # 跳过名字部分(不需要,因为已经知道是A记录) offset += 2 # 跳过指针 + # 解析答案的类型、类、TTL和数据长度 answer_type, answer_class, ttl, data_len = struct.unpack('>HHIH', response[offset:offset+10]) offset += 10 if answer_type == 1: # A记录 - ip = socket.inet_ntoa(response[offset:offset+4]) # 获取IP地址 + # 获取并返回IP地址 + ip = socket.inet_ntoa(response[offset:offset+4]) return ip offset += data_len # 跳过数据部分 + # 如果没有找到A记录,返回None return None # 发送报文