I set the hosts file on PC like this:
127.0.0.1 www.baidu.com
Then I wrote a simple test:
CURL *curl = curl_easy_init();
for (int i = 0; i < 3; i) {
if (curl) {
curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0L);
curl_easy_setopt(curl, CURLOPT_URL, "www.baidu.com");
if (i == 1)
curl_easy_setopt(curl, CURLOPT_DOH_URL, "https://dns.alidns.com/dns-query");
else
curl_easy_setopt(curl, CURLOPT_DOH_URL, NULL);
CURLcode res = curl_easy_perform(curl);
std::cout << std::endl;
std::cout << "==================================================" << std::endl;
std::cout << "Time: " << i << std::endl;
std::cout << "res = " << res << std::endl;
char *url = NULL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
if (url)
printf("Redirect to: %s\n", url);
std::cout << "==================================================" << std::endl;
curl_easy_reset(curl);
}
}
And the result is like:
==================================================
Time: 0
res = 7
Redirect to: http://www.baidu.com/
==================================================
==================================================
Time: 1
res = 0
Redirect to: http://www.baidu.com/
==================================================
==================================================
Time: 2
res = 0
Redirect to: http://www.baidu.com/
==================================================
As defined in CURLcode, r = 0
means CURLE_OK
, and r = 7
means CURLE_COULDNT_CONNECT
.
I don't understand the result. When i == 0
, I set DOH_URL
to NULL
, so it is normal that it couldn't connect. But when i == 2
, I also set DOH_URL
to NULL
, and I do reset operation, and set DNS_CACHE_TIMEOUT
to 0, why it still could connect?
CodePudding user response:
curl easy uses the existing connection of the 2nd iteration on the 3rd iteration. See Name Resolving
libcurl tries hard to re-use an existing connection rather than to create a new one. The function that checks for an existing connection to use is based purely on the name and is performed before any name resolving is attempted.
It does not change the following information kept in the handle: live connections, the Session ID cache, the DNS cache, the cookies, the shares or the alt-svc cache.