All Products
Search
Document Center

HTTPDNS:Use HTTPDNS in native iOS scenarios

Last Updated:Oct 14, 2025

This topic describes solutions for using direct IP connections when you integrate HTTPDNS into an iOS app. For information about how to integrate the SDK, see Integrate an iOS SDK.

1. Introduction

In mobile network environments, issues such as DNS hijacking and local DNS cache pollution often cause domain name resolution failures and failed network requests. For these scenarios, Alibaba Cloud HTTPDNS provides a reliable recursive resolution service. This service helps mobile apps bypass the potential risks of local DNS and improves the success rate and stability of network requests.

However, using HTTPDNS on the iOS platform requires you to replace the original domain name in a request with the resolved IP address. This can cause other problems, especially in complex scenarios that involve HTTPS and Server Name Indication (SNI). Before you integrate HTTPDNS, you need a full understanding of the potential problems and available solutions. This helps you use HTTPDNS safely and correctly in your services.

This topic describes the main problems you might encounter when using HTTPDNS on iOS. It also provides integration solutions for different scenarios and describes their pros and cons. This information helps developers quickly integrate HTTPDNS.

2. Problems with using HTTPDNS on iOS

In a mobile app, if you replace the domain name in the original URL, such as example.com, with the IP address resolved by HTTPDNS, you often encounter the following problems. These problems are closely related to how the Host field is used at different layers of the HTTPS protocol, such as the TLS/SSL layer and the HTTP layer.

  • TLS/SSL layer In HTTPS scenarios, the client first performs a TLS/SSL handshake. The handshake uses the Host from the URL to complete the following tasks:

    1. Certificate validation: Verifies that the domain name on the server certificate, which is the Common Name or Subject Alternative Name (SAN), matches the requested Host.

    2. SNI: When establishing a TLS connection, the client sends the requested domain name information, which is the Host in the URL, to the server. This allows the server to return the corresponding certificate.

  • HTTP layer After the TLS handshake is complete, the client includes the Host field in the HTTP request header. This tells the server the specific site or resource for the request. If you replace the domain name in the URL with an IP address but do not manually set the Host in the HTTP header, the server might not identify the actual domain name being accessed. This can cause the request to fail or return abnormal content.

Based on the role of the Host at different layers of the HTTPS protocol stack, simply replacing the domain name in the URL with the IP address resolved by HTTPDNS causes the following technical problems:

  1. Domain name and certificate mismatch For an HTTPS request, if you directly use the IP address resolved by HTTPDNS as the Host in the URL, the TLS layer cannot match the correct certificate domain name, which is the Common Name or SAN. This causes the SSL handshake to fail.

  2. SNI problem In SNI scenarios, a single server IP address can correspond to certificates for multiple domain names. If the client does not send the correct domain name information during the SSL handshake and sends only the IP address, the server cannot return the certificate that matches the domain name. This causes the SSL handshake to fail. Because high-level iOS network APIs, such as NSURLSession, do not expose interfaces for direct SNI configuration, it is often difficult to resolve SNI-related issues using simple methods.

  3. Host header and service addressing If you only replace the domain name in the URL with an IP address and forget to explicitly set the Host in the HTTP request header to the original domain name, the server at the HTTP layer might not identify the specific site or resource. For example, in CDN scenarios, the server depends on the Host field to distribute the correct content. If the Host is an IP address, this can cause service issues.

  4. Choice of low-level network library The built-in high-level APIs in iOS, such as NSURLSession, offer limited extensibility for custom SNI or manual certificate validation. If you want to handle SNI or modify the TLS handshake logic, you need to use lower-level interfaces, such as CFNetwork or libcurl. However, this increases development and maintenance costs.

In summary, directly replacing the domain name in the URL with the IP address resolved by HTTPDNS affects certificate validation and SNI at the TLS layer and can cause issues with the Host header at the HTTP layer. To integrate HTTPDNS on iOS, you must address these problems to ensure the reliability and security of network requests.

3. Integration solutions for plain HTTP and HTTPS non-SNI scenarios

For plain HTTP or HTTPS non-SNI scenarios, you can continue to use the system's built-in NSURLSession and standard network request logic. You only need to make some simple changes. Note that plain HTTP scenarios do not involve a TLS handshake or certificate validation. HTTPS non-SNI scenarios require certificate validation, but you can handle this by hooking the validation process in NSURLSession.

3.1 Plain HTTP scenarios

For plain HTTP requests, the network path does not involve a TLS/SSL handshake or certificate validation. The core operation for integrating HTTPDNS is performed only at the HTTP layer:

  1. Replace the Host in the request URL with the IP address resolved by HTTPDNS.

    • For example, if the original request URL is http://example.com/api and HTTPDNS resolves it to the IP address 1.2.3.4, change the URL to http://1.2.3.4/api.

  2. Explicitly set the Host in the HTTP header to the original domain name.

    • If you use NSMutableURLRequest, add request.allHTTPHeaderFields[@"Host"] = @"example.com"; to the request header. This ensures that the server can identify the correct domain name at the application layer.

Note

Pros: Simple implementation. You only need to replace the Host and set the header in the existing HTTP request, which requires minimal development effort.

Cons: Applies only to the plaintext HTTP protocol. It does not resolve certificate validation and SNI-related problems in HTTPS scenarios.

3.2 HTTPS non-SNI scenarios

For HTTPS sites that do not use SNI or that use a certificate covering only a few fixed domain names, you can integrate HTTPDNS and perform certificate validation at the NSURLSession layer as follows:

  1. Replace the Host in the request URL with the IP address resolved by HTTPDNS.

    • For example, if the original request URL is https://example.com/api and HTTPDNS resolves it to the IP address 1.2.3.4, change the URL to https://1.2.3.4/api.

  2. Explicitly set the Host in the HTTP header to the original domain name.

    • Similarly, you can set request.allHTTPHeaderFields[@"Host"] = @"example.com"; in NSMutableURLRequest.

  3. Hook the certificate validation process.

    • Because this is an HTTPS request, certificate validation is required during the TLS handshake. At this point, if you directly use the IP address as the Host for the check, a domain name and certificate mismatch problem occurs.

    • In the NSURLSessionDelegate callback method URLSession:didReceiveChallenge:completionHandler:, when you validate the serverTrust object, replace the IP address with the original domain name, such as example.com. This allows the request to pass certificate validation.

    • Code example:

      - (void)URLSession:(NSURLSession *)session
                    task:(NSURLSessionTask *)task
      didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
        completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
                                    NSURLCredential *credential))completionHandler {
          if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
              NSString *originalHost = [self getOriginalHostFromRequest:task.originalRequest];
              SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
              if ([self evaluateServerTrust:serverTrust forDomain:originalHost]) {
                  // The certificate is verified.
                  NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
                  completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
              } else {
                  // Certificate validation failed. Use the default handler.
                  completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
              }
          } else {
              completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
          }
      }
      
      - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain {
          // Create a certificate validation policy.
          NSMutableArray *policies = [NSMutableArray array];
          if (domain) {
              [policies addObject:(__bridge_transfer id) SecPolicyCreateSSL(true, (__bridge CFStringRef) domain)];
          } else {
              [policies addObject:(__bridge_transfer id) SecPolicyCreateBasicX509()];
          }
      
          // Bind the validation policy to the server certificate.
          SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef) policies);
          // Evaluate whether the current serverTrust is trusted. Apple recommends that serverTrust can be verified if the result is kSecTrustResultUnspecified or kSecTrustResultProceed. For more information, see https://developer.apple.com/library/ios/technotes/tn2232/_index.html.
          // For more information about SecTrustResultType, see SecTrust.h.
          SecTrustResultType result;
          SecTrustEvaluate(serverTrust, &result);
          return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
      }

Note

Pros:

  • Does not require you to import additional third-party libraries. It directly uses the native system NSURLSession and certificate validation logic.

  • The implementation cost is relatively manageable. It is suitable for scenarios that do not involve SNI or that require only a few domain name certificates.

Cons:

  • Cannot resolve SNI scenarios. If multiple domain names are deployed on the same IP address, such as in a CDN scenario, the handshake will still fail because the server returns the wrong certificate.

4. Integration solutions for HTTPS SNI scenarios

For SNI scenarios, which involve a single IP with multiple HTTPS domain names, a simple NSURLSession solution cannot send the correct domain name information during the SSL handshake. This causes the handshake to fail. To resolve this problem, you need to modify or specify the SNI field at a lower socket level. The following three approaches are common:

4.1 Implement a custom NSURLProtocol

iOS allows developers to intercept network requests initiated by the system by inheriting from NSURLProtocol. You can then implement the HTTP/HTTPS request logic at a lower level. You can use interfaces such as CFNetwork or NSInputStream/NSOutputStream to manually handle all network operations:

  1. Intercept requests

    • In the canInitWithRequest: method, determine whether to intercept the current request.

    • In the startLoading method, replace the domain name in the original request URL with the IP address. Retain the original domain name for subsequent certificate validation and SNI settings.

  2. Set SNI

    • Use CFStream-related APIs or the SecureTransport interface to specify kCFStreamSSLPeerName as the original domain name. This ensures that the underlying layer will include the correct domain name information during the SSL handshake.

  3. Certificate validation

    • Manually perform the certificate validation process to ensure that the domain name in the certificate matches the original domain name.

Note

Pros: Does not depend on third-party libraries. It is completely based on low-level system APIs and offers high flexibility.

Cons: High implementation and maintenance costs. You need to manually handle redirection, cookies, caching, encoding, and traffic statistics. It does not support connection reuse, so performance is average. It also poses a high maintenance risk and requires additional adaptation when the system or network environment is upgraded.

For a reference example, Alibaba Cloud provides the HttpDnsNSURLProtocolImpl.m sample implementation in the httpdns_ios_demo. You can modify or reuse it as needed.

4.2 Implement network requests using libcurl

libcurl is a cross-platform network library implemented in C. It supports manually setting the SNI field to pass the correct domain name information during the SSL handshake. This allows for successful certificate validation in scenarios where multiple domain names share the same IP address. The general process is as follows:

  1. Resolve the domain name to retrieve the corresponding IP address.

    • For example, use an API provided by HTTPDNS, such as resolveHostSyncNonBlocking:, to retrieve the IP address of the target domain name.

  2. Set the SNI and IP mapping.

    • Use CURLOPT_RESOLVE or another API to write the "domain:port:resolved IP" mapping to the internal DNS cache of curl.

    • Continue to use the original domain name as the access target for CURLOPT_URL. This ensures that the correct domain name information is included during the TLS handshake.

  3. Certificate validation

    • libcurl enables certificate validation by default. You can also use corresponding callbacks for more fine-grained checks on the certificate as needed.

The following core code snippet (pseudocode) shows how to use the result of an HTTPDNS resolution to complete a request through libcurl in iOS:

CURL *curl_handle = curl_easy_init();
if (curl_handle) {
    // For example, get IP = 1.2.3.4 from HTTPDNS, target domain = example.com, port = 443
    struct curl_slist *dnsResolve = NULL;
    dnsResolve = curl_slist_append(dnsResolve, "example.com:443:1.2.3.4");
    // Set the domain-to-IP mapping.
    curl_easy_setopt(curl_handle, CURLOPT_RESOLVE, dnsResolve);

    // Continue to use the original domain name as the URL.
    curl_easy_setopt(curl_handle, CURLOPT_URL, "https://example.com");

    // Enable SSL verification.
    curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 1L);
    curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 2L);

    // Initiate the request.
    CURLcode res = curl_easy_perform(curl_handle);

    // Check the result.
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }

    // Clean up.
    curl_easy_cleanup(curl_handle);
    curl_slist_free_all(dnsResolve);
}
Note

Pros:

  • Mature and stable. Supports a rich set of protocols and can adapt to complex network environments. Has built-in support for SNI scenarios.

Cons:

  • Requires you to compile libcurl into your iOS project. The pure C interface has a learning curve for Objective-C/Swift developers.

  • Requires you to handle custom request flows or wrap HTTP logic, such as for cookies, redirection, and caching.

4.3 Use EMASCurl

To lower the barrier to entry for using libcurl directly on iOS, the Alibaba Cloud EMAS team provides the EMASCurl library. It wraps libcurl and supports direct integration with HTTPDNS.

  1. Installation and interception

    • Provides two main ways to use it: 1) Intercept NSURLSession created from a specified NSURLSessionConfiguration. 2) Intercept the system's global [NSURLSession sharedSession].

    • For API information, see the README file on GitHub.

  2. Integration with HTTPDNS

    • Implement the EMASCurlProtocolDNSResolver protocol to pass the HTTPDNS resolution result to EMASCurl.

    • In the resolveDomain: method, call [HttpDnsService resolveHostSyncNonBlocking:] to retrieve the IP address. Then, return it to EMASCurl to complete the subsequent SNI settings and request sending.

  3. Certificate validation

    • EMASCurl relies on the certificate validation mechanism of libcurl. You can also extend or customize certificate validation through corresponding interfaces to meet your service needs.

Note

Pros:

  • Wraps the low-level capabilities of libcurl. The API is more aligned with the conventions of iOS developers.

  • Easily integrates with HTTPDNS through a DNS hook mechanism.

  • Resolves domain name passing and certificate validation problems in SNI scenarios, which reduces integration costs.

Cons:

  • Depends on third-party libraries (EMASCurl and libcurl). You need to pay attention to compatibility, version upgrades, and other factors.

  • For very complex HTTP features or custom requirements, you may still need to read and understand the internal implementation of EMASCurl to ensure service availability.

Important
  • When you integrate EMASCurl, test common HTTP/HTTPS features, such as redirection, cookies, and concurrent requests, to ensure they meet your service needs.

  • If your service has strict requirements for security or network performance, evaluate the performance of EMASCurl on the current iOS system version.

  • Ensure that requests and handshakes can be completed normally in different network environments, such as Wi-Fi, cellular networks, and proxies.

5. Summary

Choose a solution based on whether your service needs to support SNI, multiple domain names, and certificate validation. The following table compares the solutions.

Solution

Scenarios

Pros

Cons

Set only the Host and Header

Plain HTTP scenarios

- Lowest integration cost

- Applies only to the plaintext HTTP protocol

NSURLSession + Hook certificate validation

(Still requires setting the Host and Header)

HTTPS non-SNI scenarios

- Low integration cost

- Uses system APIs without additional libraries

- Does not support SNI

Custom NSURLProtocol

All scenarios

Requires more flexible low-level control

- Completely based on low-level system APIs

- High degree of freedom

- High development and maintenance costs

- No connection reuse, average performance

- Requires you to manually handle special scenarios such as redirection, cookies, caching, and encoding

libcurl

All scenarios

Cross-platform or custom HTTP flows

- Mature and stable

- Allows setting the SNI field, supports rich protocols

- Certificate validation is flexible and extensible

- The C API has a learning curve for Objective-C/Swift developers

- Requires you to wrap logic for cookies, redirection, caching, and more

EMASCurl

All scenarios

For simple integration on iOS

- Provides a good wrapper for libcurl

- Simple integration with HTTPDNS

- Implements SNI and certificate validation

- Depends on third-party libraries, requiring attention to compatibility and upgrades

- Special requirements may require reading the source code for custom development

Evaluate your business needs, including support for multiple domain names, network security requirements, compatibility, maintenance costs, and your policy on using third-party libraries. Then, choose the appropriate integration solution. Before you go online, fully test the availability and security of your network requests.