Integrate the HTTPDNS SDK in Unity to replace local DNS resolution with HTTPDNS, improving connection reliability for games and apps.
Overview
Unity is a content creation engine for 2D/3D games, VR/AR applications, mobile apps, and more.
The PdnsUnityDemo source code includes the HTTPDNS Unity plugin for HTTPDNS SDK integration.
PdnsUnityDemo is built with Unity 2019.4.21f1c1. The plugin is in the Assets/Plugins directory. You can also build your own plugin using the Alibaba Cloud DNS SDK. The plugin uses custom Gradle and Proguard files. If your project also customizes these files, merge the content.
Integration
-
Import the Plugins files.
Copy the files from the Plugins folder in PdnsUnityDemo to your Unity project > Assets > Plugins folder.
-
Configure parameters.
AlipdnsHelper.setAccountIdAndSetAccessKeyIdAndSetAccesskeySecret("accountId","accessKeyId","accesskeySecret");
AlipdnsHelper.setCacheEnable(true);
AlipdnsHelper.setSchedulePrefetchEnable(true);
AlipdnsHelper.setIspEnable(true);
AlipdnsHelper.setMaxCacheTTL(3600);
AlipdnsHelper.setMaxNegativeCache(60);
AlipdnsHelper.setScheme(1);
AlipdnsHelper.setShortEnable(false);
AlipdnsHelper.setSpeedTestEnable(true);
AlipdnsHelper.setCacheCountLimit(100);
AlipdnsHelper.setSpeedPort(80);
// Pre-resolve domain names
List<string> list = new List<string>();
list.Add("domain.example.com");
list.Add("another.example.com");
AlipdnsHelper.setPreloadDomains(list);
API reference
All APIs are in the AlipdnsHelper.cs class.
-
Required parameter:
accountId. The unique Account ID generated in the console when you register. -
Required parameters:
accessKeyIdandaccessKeySecret. Generated after you enable authentication in the console to secure user identity and prevent unauthorized access.
public static void setAccountIdAndSetAccessKeyIdAndSetAccesskeySecret(string accountId,string accessKeyId,string accessKeySecret)
-
Enable caching. After the first resolution, subsequent lookups retrieve results from the cache, which improves resolution speed.
public static void setCacheEnable(bool enable)
-
Enable or disable scheduled prefetch for expired cache entries. When enabled, the SDK refreshes expired entries every minute. This keeps the cache current but may increase DNS queries and network traffic.
public static void setSchedulePrefetchEnable(bool enable)
-
Enable or disable ISP-specific caching. When enabled, cache entries are stored separately per network environment. When disabled, a single cache is shared across all networks.
public static void setIspEnable(bool enable)
-
Set the maximum TTL for cache entries. Cache TTL does not exceed this value.
The default value is 3600 s.
public static void setMaxCacheTTL(double maxCacheTTL)
-
Set the maximum TTL for negative cache entries. Negative cache TTL does not exceed this value.
The default value is 30 s.
public static void setMaxNegativeCache(double maxNegativeCache)
-
Set the DNS request protocol. Use the
schemeproperty:scheme= 0 (default) for HTTP,scheme= 1 for HTTPS. HTTP is recommended for faster resolution.
public static void setScheme(int scheme)
-
Enable or disable short mode. When enabled, the DoH API for HTTPDNS returns a simple IP address array instead of the full JSON format (default).
public static void setShortEnable(bool enable)
-
Enable or disable IP address sorting. When enabled, resolved IP addresses are sorted fastest to slowest based on speed test results.
public static void setSpeedTestEnable(bool enable)
-
Set the maximum number of cache entries. Valid range: 100 to 500.
public static void setCacheCountLimit(int cacheCountLimit)
-
Set the port used for IP address speed testing (socket probing).
public static void setSpeedPort(int speedPort)
-
Preload domain names. Preload domains that your application needs at startup so that subsequent resolutions use the cache.
public static void setPreloadDomains(List<string> hosts)
-
Retrieve cached IP addresses for the current network environment. The method auto-detects the network type (IPv4-only, IPv6-only, or dual-stack) and returns matching IPs from cache. Returns an empty list if the cache is empty or expired (when
expiredIPEnabledis false).
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpsByCacheWithDomain(string host, bool expiredIPEnabled)
-
Retrieve cached IPv4 addresses. Returns an empty list if the cache is empty or expired (when
expiredIPEnabledis false).
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpv4ByCacheWithDomain(string host, bool expiredIPEnabled)
-
Retrieve cached IPv6 addresses. Returns an empty list if the cache is empty or expired (when
expiredIPEnabledis false).
@param host The domain name.
@param expiredIPEnabled Specifies whether to return an expired IP address.
public static List<string> getIpv6ByCacheWithDomain(string host, bool expiredIPEnabled)
-
Retrieve HTTPDNS request statistics, including information about successful and failed requests.
public static string getRequestReportInfo()
Best practices for network requests
How it works
The HTTPDNS Unity integration works as follows:
-
Cross-platform interface:
AlipdnsHelperprovides a unified API. -
Platform-specific implementation: Separate underlying implementations for the iOS and Android SDKs.
-
Automatic DNS replacement: Replaces domain names with resolved IP addresses before each network request.
-
Host header setting: Sets the correct SNI for HTTPS/SSL connections.
Network request integration
Configure the Host header when sending requests. The following sections show examples for HttpClient, HttpWebRequest, and UnityWebRequest.
HttpClient
using System;
using System.Net.Http;
using UnityEngine;
public class AlipdnsHttpClient : MonoBehaviour
{
private static readonly HttpClient httpClient = new HttpClient();
public async void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[0];
string newUrl = url.Replace(hostname, resolvedIP);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, newUrl))
{
// Important: Set the Host header to ensure SSL/SNI correctness
requestMessage.Headers.Host = hostname;
var response = await httpClient.SendAsync(requestMessage);
string content = await response.Content.ReadAsStringAsync();
Debug.Log($"Request successful: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Debug.LogError($"Request failed: {e.Message}");
}
}
}
HttpWebRequest
using System;
using System.IO;
using System.Net;
using UnityEngine;
public class AlipdnsWebRequest : MonoBehaviour
{
public void MakeRequest(string url)
{
try
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[0];
string newUrl = url.Replace(hostname, resolvedIP);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl);
request.Method = "GET";
// Important: Set the Host header to ensure SSL/SNI correctness
request.Host = hostname;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
Debug.Log($"Request successful: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Debug.LogError($"Request failed: {e.Message}");
}
}
}
UnityWebRequest (Not recommended)
UnityWebRequest cannot configure SNI correctly. SSL validation fails when the server relies on SNI to select the certificate. Use HttpClient or HttpWebRequest instead for such domains.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class AlipdnsUnityWebRequest : MonoBehaviour
{
public IEnumerator MakeRequest(string url)
{
var uri = new Uri(url);
string hostname = uri.Host;
// Use HTTPDNS to resolve the domain name
var result = AlipdnsHelper.getIpsByCacheWithDomain(hostname, true);
if (result != null && result.Count > 0)
{
string resolvedIP = result[0];
string newUrl = url.Replace(hostname, resolvedIP);
using (UnityWebRequest request = UnityWebRequest.Get(newUrl))
{
// Important: Set the Host header
request.SetRequestHeader("Host", hostname);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log($"Request successful: {request.responseCode}");
}
else
{
Debug.LogError($"Request failed: {request.error}");
}
}
}
}
}
-
This guide covers the HTTPDNS SDK for Android and iOS in Unity only.
-
To integrate the HTTPDNS SDK natively on Android or iOS, use the Android SDK development guide and iOS SDK development guide.
-
Download the PdnsUnityDemo source code for the complete HTTPDNS Unity integration sample.