Integrate the C SDK

更新时间:
复制 MD 格式

This topic describes how to integrate the HTTPDNS C software development kit (SDK).

Step 1: Prepare the environment

SDK integration requires build tools and third-party libraries. Before you integrate the SDK, you must install these dependencies on your build machine.

Name

Description

Version

git

Version control tool

1.8 or later

cmake

Build tool

3.0 or later

gcc

Compiler tool

4.5 or later

vcpkg (Optional)

Dependency library management tool

Latest version recommended

libcurl

Application-layer protocol library

7.33.0 or later

apr/apr-util

C/C++ cross-platform component library

1.5.2 or later

cjson

JSON string parsing

Latest version recommended

1. Install build tools

The build process uses Git to clone code, CMake to build the project, and gcc/g++ to compile the code. Make sure these command line interface (CLI) tools are installed on your local machine. If they are not installed, run the following commands to install them:

  • Ubuntu/Debian

    sudo  apt update
    sudo  apt install -y git cmake gcc g++
  • Alibaba Cloud Linux/CentOS Stream/Fedora

    sudo yum check-update
    sudo yum install -y git cmake  gcc  gcc-c++
  • OpenSUSE

    sudo zypper refresh
    sudo zypper install -y git cmake  gcc  gcc-c++
  • macOS

    export HOMEBREW_NO_AUTO_UPDATE=1
    brew install git gcc cmake
    Note

    Homebrew is not a built-in package manager for macOS. Before you install packages, install Homebrew.

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • Windows

2. Install dependency libraries

The SDK uses the libcurl library (version 7.33.0 or later) for network operations, the apr/apr-util library (version 1.5.2 or later) for memory management and cross-platform compatibility, and the cjson library to parse server-side response messages. The SDK does not include these external libraries. Make sure these libraries are installed and that their header file and library file directories are added to your project. You can install these C/C++ libraries using VCPKG or by manual installation.

2.1 VCPKG installation

  • Install VCPKG

  • Install the SDK dependency libraries

    • macOS/Linux

       ./vcpkg install apr apr-util curl[openssl,http2] cjson
    • Windows

      .\vcpkg.exe install apr apr-util curl[openssl,http2] cjson
      Note

      VCPKG installs libraries for the current platform by default. To cross-compile, for example, to compile an x86 library in a Windows x64 environment, you must specify a triplet. The following command is an example:

      ./vcpkg.exe install apr:x86-windows apr-util:x86-windows curl[openssl,http2]:x86-windows cjson:x86-windows

2.2 Manual installation

Note

If the cJSON developer package cannot be automatically installed using the package manager on a Unix-like platform, you can install it manually by running the following commands:

git clone https://github.com/DaveGamble/cJSON.git && cd cJSON && mkdir build && cd build && cmake  ../ && sudo make install && cd ../../ && rm -rf cJSON

Step 2: Install the SDK

  • Linux/macOS

    git clone https://github.com/aliyun/alibabacloud-httpdns-c-sdk.git
    cd alibabacloud-httpdns-c-sdk
    mkdir build
    cd build
    # If you installed the dependency libraries using VCPKG, add the CMake parameter -DVCPKG_ROOT=${path_to_vcpkg} when you build the SDK.
    cmake -DCMAKE_BUILD_TYPE=Release ../ 
    make hdns_unite_test
    sudo make install
    sudo ldconfig
  • Windows

    • Download the project.

    • Open the CMake project in Visual Studio.

    • In the configuration manager, set the CMake command parameter to -DVCPKG_ROOT=${path_to_vcpkg}

Step 3: Integrate the SDK

For more information about how to integrate the SDK, see C integration example. The following steps describe the integration procedure.

3.1 Import the SDK

To integrate the SDK, you must add the installed libraries and header files to your project. For a CMake project, add the following commands to the CMakeLists.txt file:

find_library(HTTPDNS_LIBRARY httpdns_c_sdk_static)
include_directories(${CMAKE_INSTALL_PREFIX}/include/httpdns)

3.2 Initialize the SDK

Initialize the SDK runtime environment.

 if (hdns_sdk_init() != HDNS_OK) {
        hdns_sdk_cleanup();
  }
   
  // Use the SDK API.
  
  

3.3 Create a client

 hdns_client_t *client = hdns_client_create(HTTPDNS_ACCOUNT, HTTPDNS_SECRET);
 if (client == NULL) {
    hdns_sdk_cleanup();
  }
 // Use the HTTPDNS client.
Note
  • HTTPDNS_ACCOUNT is the Account ID assigned by HTTPDNS. For more information about how to obtain the Account ID, see Product usage flow.

  • HTTPDNS_SECRET is the key used to sign the request. If authentication is not required, set this parameter to NULL. If authentication is required for domain name resolution, you must specify this parameter. For more information, see Developer configurations.

3.4 Configure the client

After you create a client instance, you can customize the HTTPDNS client configuration as follows:

// Set the server-side request timeout period in milliseconds.
hdns_client_set_timeout(client, 2000);
// Specify whether to enable the local cache.
hdns_client_set_using_cache(client, true);
// Specify whether to use HTTPS to access the HTTPDNS server.
hdns_client_set_using_https(client, true);
// Specify whether to add a signature to the request.
hdns_client_set_using_sign(client,  true);
// Set the number of retries for server-side requests.
hdns_client_set_retry_times(client, 1);
// Set the HTTPDNS resolution service cluster.
hdns_client_set_region(client, "global");
// Set the HTTPDNS scheduling cluster.
hdns_client_set_schedule_center_region(client, "cn");
// Specify whether to update the local cache after the network changes.
hdns_client_enable_update_cache_after_net_change(client, true);
// Specify whether to allow retrieval of expired cache.
hdns_client_enable_expired_ip(client, true);
// Specify whether to automatically fall back to LocalDNS.
hdns_client_enable_failover_localdns(client, true);
// Add a domain name for pre-resolution.
hdns_client_add_pre_resolve_host(client, "www.aliyun.com");
// Add an IP address for sniffing attacks.
hdns_client_add_ip_probe_item(client, "www.aliyun.com", 443);
// Customize the time-to-live (TTL).
hdns_client_add_custom_ttl_item(client, "www.aliyun.com", 120);
Important

If you set the hdns_client_set_using_https parameter to true, your billing will increase. For more information, see the Product Billing document.

3.5 Start the client

   hdns_client_start(client);

3.6 Resolve a domain name

After the client instance starts, you can call the API operations provided by the SDK to resolve domain names. The SDK provides multiple API operations for different scenarios. The following example shows how to call an API operation for synchronous resolution of a single domain name to obtain the resolution result.

    hdns_list_head_t *results = NULL;
    hdns_status_t status = hdns_get_result_for_host_sync_with_cache(client,
                                                                    MOCK_BUSINESS_HOST,
                                                                    HDNS_QUERY_AUTO,
                                                                    NULL, &results);

3.7 Select an IP address

After you obtain the resolution result, you can use a resolved IP address to access your service.

 if (hdns_status_is_ok(&status)) {
        char ip[HDNS_IP_ADDRESS_STRING_LENGTH];
        if (hdns_select_ip_randomly(results, HDNS_QUERY_AUTO, ip) == HDNS_OK) {
            mock_access_business_web_server(ip);
        }
  }
  if (hdns_status_is_ok(&status)) {
        char ip[HDNS_IP_ADDRESS_STRING_LENGTH];
        if (hdns_select_ip_randomly(results, HDNS_QUERY_AUTO, ip) == HDNS_OK) {
            mock_access_business_web_server(ip);
        }
  }
  hdns_list_free(results);

3.8 Access the service

static void mock_access_business_web_server(const char *dst_ip) {
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
        // Concatenate the service URL.
        char url[256];
        strcpy(url, "https://");
        strcat(url, MOCK_BUSINESS_HOST);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);

        // Set the pre-resolved host and IP address for HTTPS.
        struct curl_slist *dns;
        char sni[256];
        strcpy(sni, MOCK_BUSINESS_HOST);
        strcat(sni, ":443:");
        strcat(sni, dst_ip);
        dns = curl_slist_append(NULL, sni);
        curl_easy_setopt(curl, CURLOPT_RESOLVE, dns);
        // Set the response result callback.
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_callback);
#if defined(_WIN32)
        curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
#endif
        // Initiate an HTTP request.
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed, url=%s, ip=%s, error=%s\n",
                    url,
                    dst_ip,
                    curl_easy_strerror(res));
        }
        // Release resources related to service access.
        curl_slist_free_all(dns);
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
}

3.9 Clean up the client

When the client is no longer in use, release it.

hdns_client_cleanup(client);

3.10 Clean up the SDK

When the SDK is no longer in use, release it.

hdns_sdk_cleanup();