微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 libcurl 尝试 dns 中的所有服务器?

如何解决如何使用 libcurl 尝试 dns 中的所有服务器?

我需要使用 Linux/C++/libcurl 定期随机测试通过单个 DNS 名称可用的多个服务器的响应,例如

$ host example.com
n1.example.com 1.2.3.4
n2.example.com 1.2.3.5
n3.example.com 1.2.3.6

列表发生变化。当我尝试 https://example.com 时,libcurl 在 TTL 范围内始终使用相同的 IP,并且我无法切换到下一个主机。有 CURLOPT_DNS_CACHE_TIMEOUT setopt,但将其设置为零无济于事 - 即使我完全重新创建 easycurl 对象,我仍然获得相同的 IP。因此,这无济于事:curl - How to set up TTL for dns cache & How to clear the curl cache

我当然可以手动解析 DNS 名称并进行迭代,但有其他选择吗?随机投票没问题。我看到 curl 使用 c-ares。有没有办法清理那里的缓存,它会有帮助吗?

解决方法

如果不自己解决问题,我无法完全使用 curl 完成我需要的操作,但有一些发现可以与其他人分享:

首先,作为一个写得很好的TCP客户端,curl会从上到下尝试DNS列表中的主机,直到连接成功。从那时起,即使它返回一些更高级别的错误(例如 SSL 错误或 HTTP 500),它也会使用该主机。这对所有重大案件都有好处。

较新 curl 版本的 curl 命令行有 --retry--retry-all-errors - 但不幸的是,libcurl 中没有这些东西。该功能目前正在增强,截至 2021 年 7 月 14 日,尚未发布将枚举所有 DNS 主机的版本,直到有一个返回 HTTP 200 的主机为止。相反,已发布的 curl 版本(我尝试了 7.76 和 7.77)将始终使用同一主机重试。但是每晚构建 (2021-07-14) 确实枚举了所有 DNS 主机。以下是两次重试和三个不存在的主机时的行为(注意,如果任何主机返回 HTTP 5xx,就会发生重试):

$ ./src/curl http://nohost.sureno --trace - --retry 2 --retry-all-errors
    == Info:   Trying 192.168.1.112:80...
    == Info: connect to 192.168.1.112 port 80 failed: No route to host
    == Info:   Trying 192.168.1.113:80...
    == Info: connect to 192.168.1.113 port 80 failed: No route to host
    == Info:   Trying 192.168.1.114:80...
    == Info: connect to 192.168.1.114 port 80 failed: No route to host
    == Info: Failed to connect to nohost.sureno port 80 after 9210 ms: No route to host
    == Info: Closing connection 0
    curl: (7) Failed to connect to nohost.sureno port 80 after 9210 ms: No route to host
    Warning: Problem (retrying all errors). Will retry in 1 seconds. 2 retries
    Warning: left.
    == Info: Hostname nohost.sureno was found in DNS cache
    == Info:   Trying 192.168.1.112:80...
    == Info: connect to 192.168.1.112 port 80 failed: No route to host
    == Info:   Trying 192.168.1.113:80...
    == Info: connect to 192.168.1.113 port 80 failed: No route to host
    == Info:   Trying 192.168.1.114:80...
    == Info: connect to 192.168.1.114 port 80 failed: No route to host
    == Info: Failed to connect to nohost.sureno port 80 after 9206 ms: No route to host
    == Info: Closing connection 1
    curl: (7) Failed to connect to nohost.sureno port 80 after 9206 ms: No route to host
    Warning: Problem (retrying all errors). Will retry in 2 seconds. 1 retries

这种行为对 libcurl 的用户非常有帮助,但不幸的是,这些重试标志目前没有映射到 curl_easy_setopt。因此,如果您将 --libcurl 提供给命令行,您将看不到任何与重试相关的代码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。