如何使用 libcurl 获取具有特定服务器 IP 的页面

How can I use libcurl to get a page with a specific server IP

我正在通过 libcurl 抓取页面。我需要使用特定的 IP 来获取页面。这个 ip 是由 DNS 解析器生成的。所以我可以跳过 libcurl 中的 getaddrinfo 并花费更少的时间。

我问了一个问题,但我发现这不是我想要的。

您可以 "pre-populate" libcurl 的 DNS 缓存 CURLOPT_RESOLVE,然后您可以像往常一样继续使用 URL 中的主机名。

这是一个告诉 curl example.com 位于 127.0.0.1

的小示例
CURL *curl;
struct curl_slist *host = NULL;
host = curl_slist_append(NULL, "example.com:80:127.0.0.1");

curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
  curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
  res = curl_easy_perform(curl);

  /* always cleanup */
  curl_easy_cleanup(curl);
}

curl_slist_free_all(host);

另一种选择是在 URL 中使用正确的 IP 并发送自定义主机:header,其中包含正确的主机名。

CURLOPT_DNS_LOCAL_IP4 设置 "the local IPv4 address that the resolver should bind to" 因此是一个完全不同的功能)