All Products
Search
Document Center

HTTPDNS:Use libcurl for C or C++ to access a website through an IP address resolved by HTTPDNS

Last Updated:Jan 16, 2024

HTTPDNS provided by Enterprise Mobile Application Studio (EMAS) can be accessed only from Android or iOS devices by using HTTPDNS SDKs. You can use libcurl for C or C++ on other devices to obtain IP addresses resolved by HTTPDNS to access websites.

Background information

When you use IP addresses resolved by HTTPDNS to access websites, you must perform the following operations:

  • Configure the Host header in the request.

  • Configure SNI in the request.

  • Verify the certificates in the request.

Prerequisites

libcurl for C or C++ is installed.

Procedure

1. Use the HTTP API of HTTPDNS to resolve the domain name of the website of the website you want to access to an IP address. For more information, see Resolve a domain name.

2. Use the custom addresses for hosts feature provided by libcur for C or C++ to access the website through the IP address resolved by HTTPDNS. For more information, see Name resolving.

Example

In this example, you want to access a website https://example.com/ with the following domain name and IP address:

  • Domain name: example.com

  • IP address: 192.168.XX.XX

You can initiate a request by using a curl command or libcurl to access the website through the IP address.

  • Request based on a curl command

$ curl --max-time 5 --resolve example.com:4XX:192.168.XX.XX https://example.com/
  • Request based on libcurl

#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);

        /* Specify the domain name and the IP address resolved by HTTPDNS. * /
        struct curl_slist *dns;
        dns = curl_slist_append(NULL, "example.com:4XX:192.168.XX.XX");
        curl_easy_setopt(curl, CURLOPT_RESOLVE, dns);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));
        }

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

    curl_global_cleanup();

    return 0;
}