You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

组织子域名枚举遇socket.gaierror错误:Errno 11001 getaddrinfo failed

解决内部子域名解析时socket.gaierror错误的问题

问题重现

你在执行组织子域名枚举任务时,编写了以下Python代码读取文本文件中的子域名并解析IP:

import socket

file = open(r'C:\Users****\Downloads\sublist.txt')
domain_list = []
for x in file.readlines():
    domain_list.append(x.rstrip())
for y in domain_list:
    print(y + ' -> ' + socket.gethostbyname(y))

当文件包含组织内部子域名时,脚本抛出socket.gaierror: [Errno 11001] getaddrinfo failed,但公共域名(如google.com)能正常解析,且直接执行socket.gethostbyname('组织子域名')可成功获取IP,同时已连接组织VPN。

问题原因分析

最可能的原因是文本文件中的子域名包含隐藏空白字符(如制表符、全角空格、残留的特殊换行符),rstrip()仅移除了右侧的常规换行符,无法处理其他空白内容,导致传递给socket.gethostbyname()的域名格式无效,进而触发解析错误。

解决方案

1. 彻底清理域名中的空白字符

使用strip()替代rstrip(),同时过滤空行,确保每个域名都是纯净的有效字符串:

import socket

# 用with语句自动管理文件句柄,避免资源泄漏
with open(r'C:\Users****\Downloads\sublist.txt', 'r', encoding='utf-8') as file:
    # 过滤空行,并用strip()清理所有前后空白字符
    domain_list = [line.strip() for line in file if line.strip()]

for domain in domain_list:
    try:
        ip = socket.gethostbyname(domain)
        print(f"{domain} -> {ip}")
    except socket.gaierror:
        print(f"无法解析域名: {domain} - 检查域名格式或网络连接")

2. 可选:添加域名格式校验

可以加入简单的正则校验,提前排除格式无效的条目:

import socket
import re

# 简单匹配域名格式的正则表达式
DOMAIN_PATTERN = re.compile(r'^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')

with open(r'C:\Users****\Downloads\sublist.txt', 'r', encoding='utf-8') as file:
    domain_list = []
    for line in file:
        cleaned_domain = line.strip()
        if cleaned_domain and DOMAIN_PATTERN.match(cleaned_domain):
            domain_list.append(cleaned_domain)
        elif cleaned_domain:
            print(f"跳过无效格式的域名: {cleaned_domain}")

for domain in domain_list:
    try:
        ip = socket.gethostbyname(domain)
        print(f"{domain} -> {ip}")
    except socket.gaierror:
        print(f"解析失败: {domain}")

额外提示

  • 使用with语句处理文件是更规范的写法,能自动关闭文件,避免资源占用。
  • 添加异常处理可以让脚本更健壮,不会因为单个域名解析失败而中断整个任务。
  • 如果问题仍存在,可以打印每个读取到的域名的原始字符(比如用repr(domain)),排查是否存在隐藏的特殊字符。

内容的提问来源于stack exchange,提问作者Biswa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:03:28