すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud DNS:SDK for iOS開発者ガイド

最終更新日:Jan 23, 2025

このトピックでは、Alibaba Cloud iOS用パブリックDNS SDKとその使用方法について説明します。

1. 概要

Alibaba CloudパブリックDNS SDKは、モバイル開発者にドメインネームシステム (DNS) 解決サービスを提供するためにAlibaba Cloudによって開発されました。

このSDKにより、モバイル開発者はiOSアプリでAlibaba CloudパブリックDNSを使用できます。 これは、DNS解決エラーを防止し、低コストでDNS要求の正確なスケジューリングを実施する。 デモプロジェクトのソースコードは、SDKをiOSアプリと統合し、iOSアプリでAlibaba CloudパブリックDNSを使用する方法の例を示しています。

iOS 14オペレーティングシステムでは、DNS over TLS (DoT) とDNS over HTTPS (DoH) の2つのネイティブDNS暗号化プロトコルがサポートされています。 Alibaba CloudパブリックDNSを暗号化DNSのデフォルトリゾルバーとして設定する方法の詳細については、「iOS 14のネイティブ暗号化DNS」をご参照ください。

SDKは、Alibaba CloudパブリックDNSのJSON API for DoHをカプセル化します。 SDKは、iOSアプリがDNS解決を実行するための機能も提供し、有効期間 (TTL) および最長期間 (LRU) ポリシーに基づく効率的なドメイン名キャッシュをサポートします。 SDKには、Alibaba CloudパブリックDNSの機能に基づく次の利点があります。

  • 使いやすさ

    Alibaba CloudパブリックDNSを使用するには、SDKをアプリと統合するだけです。 これにより、DNS解決サービスをより簡単で便利な方法で使用できます。

  • DNS解決なしの遅延

    SDKはLRUキャッシュアルゴリズムを使用します。 これにより、DNS解決から取得したIPアドレスがオンプレミスサーバーにキャッシュされます。 また、SDKは自動的にキャッシュを更新し、TTLに基づいて期限切れのデータを削除します。 このようにして、キャッシュされたデータは常に有効であり、DNS解決を遅延なく効果的に実装できます。

2. SDK 統合

iOS開発者は、次のいずれかの方法を使用して、SDKをiOSアプリと統合できます。

  • CocoaPodsを使用した自動統合

  • マニュアル統合

2.1 CocoaPodsを使用した自動統合

1. Podfileでライブラリの場所 (ライブラリのマスターブランチを含む) を指定します。

source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/aliyun/aliyun-specs.git'

2. Xcodeプロジェクトのターゲットディレクトリに依存関係を追加します。

pod 'AlicloudPDNS'

2.2 マニュアル統合

  1. 再帰的解決 (パブリックDNS) ページの [暗号化アクセス (HTTP) 、DoH、およびDoT) タブの [アクセスガイド] セクションで、[iOS用SDKのダウンロード] をクリックして、Alibaba CloudパブリックDNS SDK for iOSのパッケージをダウンロードします。

  2. sdkのpdns-SDK-ios.frameworkフォルダーをiOSアプリに追加します。

  3. 次のシステムライブラリをアプリにインポートします。

    • Foundation.framework

    • SystemConfiguration.framework

    • CoreFoundation.framework

    • CoreTelephony.framework

  4. Xcodeプロジェクトの [ビルド設定] ウィンドウで、-ObjCを他のリンカーフラグに追加します。

2.3 SDKの初期化

Alibaba Cloud DNSコンソールにアプリを登録し、アプリのアカウントIDを取得し、認証用のAccessKey IDとAccessKeyシークレットを取得します。 SDKをアプリと統合した後、SDKを初期化します。

重要

IPアドレスの解決の失敗を避けるために、SDKができるだけ早く初期化されていることを確認してください。

アプリでapplication:didFinishLaunchingWithOptions: メソッドを呼び出して、SDKを初期化します。 メソッドで次のコードを使用します。

DNSResolver *resolver = [DNSResolver share];
//setAccountId:@"******": Replace ****** with the account ID displayed on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
//andAccessKeyId:@"********": Replace ****** with the AccessKey ID created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
//andAccesskeySecret:@"********": Replace ****** with the AccessKey secret created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
// Specify an array of domain names whose cached DNS results are automatically updated after expiration. You can specify up to 10 domain names.
[resolver setKeepAliveDomains:@[@"Domain Name 1",@"Domain Name 2"]];
// Preload the DNS results of domain names that you want to resolve.
[resolver preloadDomains:@[@"Domain Name 1", @"Domain Name 2", @"Domain Name 3"] complete:^{
    // The DNS results of all specified domain names are preloaded.      
}];

3. API リファレンス

3.1 共通設定

3.1.1 必須パラメーターの指定

アカウントID、AccessKey ID、およびAccessKey Secretパラメーターが必要です。 アカウントIDパラメーターの値は、Alibaba Cloud DNSコンソールでアプリを登録した後に生成されます。 認証機能は、権限のない第三者によるユーザIDの盗難を防止する。 Alibaba Cloud DNSコンソールでAccessKeyペアを作成できます。 詳細については、「サービス認証」をご参照ください。 次のコードは、アプリでパラメーターを指定する方法の例を示しています。

//setAccountId:@"******": Replace ****** with the account ID displayed on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
//andAccessKeyId:@"********": Replace ****** with the AccessKey ID created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
//andAccesskeySecret:@"********": Replace ****** with the AccessKey secret created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
[[DNSResolver share] setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
警告
  • アカウントID、AccessKey ID、AccessKey Secret、またはアプリケーションの実行中に生成されたデータのデータ漏洩を防ぐために、SDKのデバッグログを無効にすることを推奨します。

  • より良いデモンストレーションのために、アカウントID、AccessKey ID、およびAccessKey Secretがサンプルコードで使用されています。 これらのパラメータは、計量と請求に密接に関連しています。 悪意のある逆コンパイルによる情報漏洩を防ぐため、これらの機密情報を平文形式で渡さないことを推奨します。 値を指定しない場合、これらのパラメーターは暗号化およびエンコードする必要があります。 さらに、アプリケーションを展開する前に、難読化を有効にしてアプリケーションを強化することをお勧めします。 そうしないと、不正な第三者がコードを逆コンパイルしてアカウントID、AccessKey ID、AccessKey Secretを傍受する可能性があります。

3.1.2 解決プロトコルの指定

SDKは、HTTPまたはHTTPSを介したDNS解決をサポートしています。 schemeパラメーターを指定することで、HTTPまたはHTTPSでDNS解決を実行するかどうかを指定できます。

HTTPSは高いセキュリティを提供するため、SDKはデフォルトでHTTPSを介してDNS解決を実行します。 また、HTTPSの使用を推奨します。 パブリックDNSは、HTTPを介したDNS解決回数に基づいて課金されます。 HTTPSを介した1回のDNS解決は、HTTPを介した5回のDNS解決に相当します。 ビジネス要件に基づいて適切なプロトコルを選択できます。 次のコードは、schemeパラメーターを指定する方法の例を示しています。

[DNSResolver share].scheme = DNSResolverSchemeHttps;

3.1.3 キャッシュ機能を有効にするかどうかを指定する

SDKを使用して、キャッシュ機能を有効にするかどうかを指定できます。 この機能が有効になっている場合、最初の解決から取得されたデータはキャッシュされ、キャッシュされたデータは後続の解決要求に対して優先的に返されます。 これにより、DNS解決が大幅に加速されます。

デフォルトでは、キャッシュ機能はSDKで有効になっています。 キャッシュ機能を無効にするには、cacheEnableパラメーターをNOに設定します。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].cacheEnable=NO;

3.1.4 キャッシュ保持機能を有効にするかどうかを指定する

キャッシュ機能が有効になっている場合、一部のドメイン名に対してキャッシュ保持機能を有効にできます。 その後、SDKは1分ごとに期限切れのキャッシュデータを新しいデータに自動的に置き換えます。 このようにして、キャッシュ内のデータをタイムリーに更新することができますが、DNS解決がより頻繁に実行され、クライアントのデータ転送も増加します。 キャッシュ保持機能を有効にしない場合、SDKは期限切れのキャッシュデータを新しいデータに自動的に置き換えません。 キャッシュデータは、DNS解決メソッドを呼び出した場合にのみ更新されます。 次のコードは、一部のドメイン名に対してキャッシュ保持機能を有効にする方法の例を示しています。
// You can specify up to 10 domain names.
[[DNSResolver share] setKeepAliveDomains:@[@"www.taobao.com",@"www.aliyun.com"]];
説明

メリット

1. キャッシュされたDNSレコードは、TTL期間が終了する前に更新できます。

2. DNSの結果をプリロードして、最初の解決でレイテンシをゼロにすることができます。

欠点

1. TTL期間の75% が経過すると、信頼できるDNSサーバーに対してDNSリクエストが再度開始されるため、追加料金が発生します。

3.1.5 事前解決ドメイン名

SDKを使用して、キャッシュ機能を有効にできます。 この機能が有効になっている場合、最初の解決から取得されたデータはキャッシュされ、キャッシュされたデータは後続の解決要求に対して優先的に返されます。 これにより、後続の解像度のレイテンシが0ミリ秒に短縮されます。 したがって、アプリの起動後に解決するドメイン名を事前に解決することをお勧めします。

サンプルコード:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   
   DNSResolver *resolver = [DNSResolver share];
   //setAccountId:@"******": Replace ****** with the account ID displayed on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   //andAccessKeyId:@"********": Replace ****** with the AccessKey ID created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   //andAccesskeySecret:@"********": Replace ****** with the AccessKey secret created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   [resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
   resolver.cacheEnable = YES;
   // Preload the DNS results of domain names that you want to resolve.
   [resolver preloadDomains:@[@"Domain Name 1", @"Domain Name 2", @"Domain Name 3"] complete:^{
       // The DNS results of all specified domain names are preloaded.
       
   }];
   
   return YES;
}

3.2 その他の詳細設定

3.2.1 サーバのIPv6アドレスを使用するかどうかを指定する

Alibaba CloudパブリックDNSは、IPv4およびIPv6デュアルスタックアクセスをサポートしています。 デフォルトでは、SDKはIPv4アドレスを使用してDNSサーバーにアクセスします。

IPv6アドレスを使用してDNSサーバーにアクセスする場合は、現在のネットワークがIPv6アドレスをサポートしていることを確認し、ipv6EnableパラメーターをYESに設定してIPv6アクセスを有効にします。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].ipv6Enable = YES;

3.2.2 ショートモードを有効にする

Alibaba CloudパブリックDNSのDoH用のJSON APIによって返されるデータは、JSON形式またはIPアドレスの配列にすることができます。 デフォルトでは、SDKはJSON形式を使用します。

返されたデータをIPアドレスの配列にする場合は、shortEnableパラメーターを設定してショートモードを有効にします。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].shortEnable = YES;

3.2.3 DNS解決結果をキャッシュできるドメイン名の最大数を指定します。

キャッシュ機能が有効になっている場合、DNS解決結果をキャッシュできるドメイン名の最大数を指定できます。 有効な値: 100〜500。

デフォルトでは、SDKを使用して、最大100個のドメイン名のDNS解決結果をキャッシュできます。 cacheCountLimitパラメーターを指定して、キャッシュエントリの最大数を指定できます。

[DNSResolver share].cacheCountLimit = 200;

3.2.4 IPアドレスの接続速度テストを有効にするかどうかを指定する

SDKを使用して、IPアドレスの接続速度テストを有効にできます。 この機能を有効にすると、接続速度が最も速いDNS解決結果が優先的に返されます。 DNS解決結果は、接続速度によって降順にソートされる。

デフォルトでは、この機能はSDKで無効になっています。 この機能を有効にするには、speedTestEnableをYESに設定します。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].speedTestEnable=YES;

3.2.5 接続速度テストモードの指定

接続速度テストモードを指定できます。 この機能が有効になっており、speedPortパラメーターが0に設定されている場合、インターネット制御メッセージプロトコル (ICMP) パケットが接続速度を検出するために使用されます。 speedPortパラメーターが80、443、またはその他の有効な値に設定されている場合、ソケットで指定されているポートが接続速度の検出に使用されます。

SDKのこのパラメーターのデフォルト値は0です。 ソケットで指定されたポートを検出用に使用するには、speedPortパラメーターを指定する必要があります。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].speedPort = 80;

3.2.6 ISPネットワークに基づいてドメイン名キャッシュを有効にするかどうかを指定する

SDKを使用して、インターネットサービスプロバイダー (ISP) ネットワークに基づくドメイン名キャッシュを有効にできます。 この機能を有効にすると、キャッシュされたDNS解決結果はネットワーク環境に応じて別々に保存されます。 この機能を無効にすると、同じキャッシュドメイン名データが異なるネットワークで使用されます。

デフォルトでは、この機能はSDKで無効になっています。 この機能を有効にするには、ispEnableパラメーターをYESに設定します。 次のセクションでは、サンプルコードを示します。

[DNSResolver share].ispEnable = YES;

3.2.7 ネガティブキャッシュの最大TTL期間を指定する

SDKを使用して、否定的な無効キャッシュの最大TTL期間を指定できます。これは、ドメインの未設定のIPアドレスで解決中にIPが返されない場合に発生します。 maxNegativeCacheパラメーターを設定した場合、ネガティブキャッシュの最大TTLはこのパラメーターの値を超えることはできません。

このパラメーターのデフォルト値は、SDKでは30秒です。 次のセクションでは、サンプルコードを示します。
[DNSResolver share].maxNegativeCache = 30;

3.2.8 DNS結果をキャッシュするための最大TTL期間を指定する

SDKを使用して、DNS結果をキャッシュするための最大TTLを指定できます。 maxCacheTTLパラメーターを設定した場合、DNS結果をキャッシュするための最大TTLはこのパラメーターの値を超えることはできません。

このパラメーターのデフォルト値は、SDKで秒単位で3600されます。 次のセクションでは、サンプルコードを示します。
[DNSResolver share].maxCacheTTL= 3600;
3.2.9 キャッシュの期限が切れないように設定する
[DNSResolver share].immutableCacheEnable = NO;// By default, the cache is set to expire.
重要

SDKは、3つのキャッシュ更新メカニズムを提供します。

  • キャッシュが期限切れにならない: キャッシュを期限切れにならないように設定すると、アプリはアプリの実行中にキャッシュが常に有効であると判断し、期限切れチェックを実行せず、期限切れのキャッシュを更新しません。 これにより、DNS解決の回数を最小限に抑えることができます。

    メソッド: [DNSResolver share].immutableCacheEnable = YESパラメーターを使用して、キャッシュが期限切れにならないように設定できます。

  • キャッシュはアクティブに更新されます。このメカニズムは、DNS要求が常にキャッシュされたDNS結果と一致するようにするためです。 権限のあるDNS解決ルールが変更された場合、この方法を使用して、解決中にDNSリクエストがキャッシュされたDNS結果と常に一致するようにします。 これにより、DNS解決のためのネットワーク待ち時間が短縮され、最新のDNSレコードが確実にキャッシュされます。 最大10個のドメイン名に対してキャッシュ保持機能を有効にすることを推奨します。

    メソッド: [[DNSResolver share] setKeepAliveDomains:@[@ "custom domain name 1",@ "custom domain name 2"]]] パラメーターを使用して、キャッシュをアクティブに更新するように設定できます。

  • 次の2つの方法を使用して、キャッシュを受動的に更新するように設定できます。

    • - (void)getIpv4DataWithDomain :( NSString *)domain complete :( void(^)(NSArray<NSString *> * dataArray))complete resolutionメソッドを使用する場合、キャッシュからIPv4アドレスが取得され、DNS結果がキャッシュに存在し、有効期限が切れない場合はDNS結果が返されます。 キャッシュにDNS結果が存在しない場合、またはキャッシュされたDNS結果が期限切れになった場合、DNS要求はDNS結果のサーバーに再帰的に送信されます。 取得したDNS結果は返され、キャッシュされます。 この方法は、DNS結果に対してより高い精度が必要なシナリオ向けに設計されています。

    • - (NSArray<NSString *> *)getIpv4ByCacheWithDomain :( NSString *)domain andExpiredIPEnabled :( BOOL)enable解決メソッドを使用する場合: IPV4アドレスはキャッシュから取得されます。 enableパラメーターを設定して、期限切れのDNS結果をキャッシュに返すかどうかを指定できます。

      説明: キャッシュにデータが存在しない場合は、nullが返されます。 この場合、DNS結果を取得するために非同期要求が開始され、それが返されてキャッシュに格納されます。 enableYESに設定した場合、期限切れのキャッシュIPアドレスが返される可能性があります。 enableNOに設定した場合、キャッシュの有効期限が切れるとnullが返され、非同期リクエストの開始後にキャッシュが更新されます。

3.2.10 timeoutパラメーターの設定

timeoutパラメーターは、DNS解決のタイムアウト期間を指定します。 デフォルトのタイムアウト時間は3秒です。 ビジネス要件に基づいて、カスタムのタイムアウト期間を指定できます。 タイムアウト時間を2〜5秒の範囲内の値に設定することを推奨します。

4. サービスAPI操作

サンプルコード:

/// Pre-resolve an array of domain names. After you start your app, you can call this operation to cache DNS resolution results. This accelerates subsequent DNS resolution.
/// Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack. Then, resolve the array of the domain names to the IP addresses that are supported by the current network environment.
/// @param domainArray The array of domain names that you want to resolve.
/// @param complete     Return DNS resolution results.
- (void)preloadDomains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;

/// Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack. Then, resolve the domain name to the array of IP addresses that are supported by the current network environment. 
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP addresses. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP addresses. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return all IP addresses to which the domain name is resolved.
- (void)getIpsDataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;

/// Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack. Then, obtain the array of IP addresses that are supported by the current network environment from the cache without delay.  
/// If no data is cached, nil is returned. If the cached data exists and the enable parameter is set to YES, the cached data is returned. If cached data expires, the domain name is asynchronously resolved to update the cached data. If the cached data exists and the enable parameter is set to NO, nil is returned when the cached data expires, and the domain name is asynchronously resolved to update the cached data. 
/// @param domain   The domain name that you want to resolve.
/// @param enable   Specify whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpsByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;

/// Obtain an array of information about the IPv4 addresses to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return the information about all the IPv4 addresses to which the domain name is resolved.
- (void)getIpv4InfoWithDomain:(NSString *)domain complete:(void(^)(NSArray<DNSDomainInfo *> *domainInfoArray))complete;

/// Obtain an array of information about the IPv6 addresses to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return the information about all the IPv6 addresses to which the domain name is resolved.
- (void)getIpv6InfoWithDomain:(NSString *)domain complete:(void(^)(NSArray<DNSDomainInfo *> *domainInfoArray))complete;

/// Obtain the information about an IPv4 address to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return the information about an IPv4 address to which the domain name is resolved.
- (void)getRandomIpv4InfoWithDomain:(NSString *)domain complete:(void(^)(DNSDomainInfo *domainInfo))complete;

/// Obtain the information about an IPv6 address to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return the information about an IPv6 address to which the domain name is resolved.
- (void)getRandomIpv6InfoWithDomain:(NSString *)domain complete:(void(^)(DNSDomainInfo *domainInfo))complete;

/// Obtain the array of IPv4 addresses to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return all IPv4 addresses to which the domain name is resolved.
- (void)getIpv4DataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;

/// Obtain the array of IPv6 addresses to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return all IPv6 addresses to which the domain name is resolved.
- (void)getIpv6DataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;

/// Obtain an IPv4 address to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return one of the IPv6 addresses to which the domain name is resolved.
- (void)getRandomIpv4DataWithDomain:(NSString *)domain complete:(void(^)(NSString *data))complete;

/// Obtain an IPv6 address to which a domain name is resolved.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return one of the IPv6 addresses to which the domain name is resolved.
- (void)getRandomIpv6DataWithDomain:(NSString *)domain complete:(void(^)(NSString *data))complete;

/// Pre-resolve an array of domain names to IPv4 addresses. After you start your app, you can call this operation to cache the DNS resolution results. This accelerates subsequent DNS resolution.
/// @param domainArray  The array of domain names that you want to resolve.
/// @param complete         Return DNS resolution results.
- (void)preloadIpv4Domains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;

/// Pre-resolve an array of domain names to IPv6 addresses. After you start your app, you can call this operation to cache the DNS resolution results. This accelerates subsequent DNS resolution.
/// @param domainArray  The array of domain names that you want to resolve.
/// @param complete         Return DNS resolution results.
- (void)preloadIpv6Domains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;

/// Query the cache to obtain an IPv4 address to which the domain name is mapped.  
/// If no cached data exists, nil is returned. If the cached data exists and the enable parameter is set to YES, the cached data is returned. If cached data expires, the domain name is asynchronously resolved to update the cached data. If the cached data exists and the enable parameter is set to NO, nil is returned when the cached data expires, and the domain name is asynchronously resolved to update the cached data. 
/// @param domain   The domain name that you want to resolve.
/// @param enable   Specify whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpv4ByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;

/// Query the cache to obtain an IPv6 address to which the domain name is mapped.  
/// If no cached data exists, nil is returned. If the cached data exists and the enable parameter is set to YES, the cached data is returned. If cached data expires, the domain name is asynchronously resolved to update the cached data. If the cached data exists and the enable parameter is set to NO, nil is returned when the cached data expires, and the domain name is asynchronously resolved to update the cached data. 
/// @param domain   The domain name that you want to resolve.
/// @param enable   Specify whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpv6ByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;

/// Collect statistical information.
-(NSArray *)getRequestReportInfo;

5. サンプルAPI呼び出し

5.1 基本情報の設定

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   // The only method for initialization.
   DNSResolver *resolver = [DNSResolver share];
   //setAccountId:@"******": Replace ****** with the account ID displayed on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   //andAccessKeyId:@"********": Replace ****** with the AccessKey ID created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   //andAccesskeySecret:@"********": Replace ****** with the AccessKey secret created on the Access Configuration tab of the Recursive Resolution (Public DNS) page in the Alibaba Cloud DNS console.
   [resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
   // Specify an array of domain names whose cached DNS results are automatically updated after expiration. You can specify up to 10 domain names.
	 [resolver setKeepAliveDomains:@[@"Domain Name 1",@"Domain Name 2"]];
   // Preload the DNS results of domain names that you want to resolve. The DNS results can be obtained in advance and cached.
   [resolver preloadDomains:@[@"Domain Name 1", @"Domain Name 2", @"Domain Name 3"] complete:^{
       // The DNS results of all specified domain names are preloaded.
       
   }];
   return YES;
}

5.2 操作を呼び出してドメイン名を解決する

SDKは、さまざまなDNS解決方法を提供します。 詳細については、ヘッダーファイルDNSResolver.hをご参照ください。 次のセクションでは、IPv4-only、IPv6-only、IPv4/IPv6デュアルスタックなどのネットワーク環境でサポートされているIPアドレスタイプを自動的に検出するDNS解決方法について説明します。

API操作宣言:

/// Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack. Then, resolve the domain name to the array of the IP addresses that are supported by the current network environment.
/// If the caching feature is enabled, the system preferentially tries to obtain cached data. If no data is cached or the cached data expires, a DNS request is sent to obtain the corresponding IP address. If the caching feature is not enabled, a DNS request is sent to obtain the corresponding IP address. 
/// @param domain           The domain name that you want to resolve.
/// @param complete       Return all addresses to which the domain name is resolved.
- (void)getIpsDataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;

次のサンプルコードは、操作を呼び出す方法の例を示しています。

[[DNSResolver share] getIpsDataWithDomain:@"www.taobao.com" complete:^(NSArray<NSString *> *dataArray) {
    // dataArray is an array of IP addresses that correspond to the domain name www.taobao.com.
   if (dataArray.count > 0) {
       // TODO: Use the IP address to send a business request.
   }    
}];

5.3 DNS解決結果をキャッシュから取得する

API操作宣言:

/// Automatically detect the IP address type that is supported by the current network environment, such as IPv4-only, IPv6-only, or IPv4/IPv6 dual-stack. Then, obtain the array of IP addresses that are supported by the current network environment from the cache without delay.  
/// If no cached data exists, nil is returned. If the cached data exists and the enable parameter is set to YES, the cached data is returned. If cached data expires, the domain name is asynchronously resolved to update the cached data. If the cached data exists and the enable parameter is set to NO, nil is returned when the cached data expires, and the domain name is asynchronously resolved to update the cached data. 
/// @param domain   The domain name that you want to resolve.
/// @param enable   Specify whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpsByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;

サンプルコード:

NSArray *result = [[DNSResolver share] getIpsByCacheWithDomain:@"Domain name" andExpiredIPEnabled:YES];
// Obtain an IP address that maps the domain name from the cache.
if (result.count > 0) {
   // TODO: Use the IP address to send a business request.
   
}

注: DNS解決を実行しなくても、キャッシュからDNS解決結果をすばやく取得できます。 解決するドメイン名が以前に解決されていない場合、またはキャッシュ内のDNS解決結果が期限切れになり、有効化パラメータをNOに設定すると、nilが返されます。

5.4 キャッシュの削除

API操作宣言:

/// Set the hostArray parameter to an array of domain names for which you want to clear the cached DNS results. If you want to clear all data, set this parameter to nil or an empty array.
-(void)clearHostCache:(NSArray <NSString *>*)hostArray;

サンプルコード:

[[DNSResolver share] clearHostCache:@[@"Domain Name 1", @"Domain Name 2"]];

5.5 統計情報の収集

API操作宣言:

/// Collect statistical information.
-(NSArray *)getRequestReportInfo;

サンプルコード:

NSArray *array = [[DNSResolver share] getRequestReportInfo];

データ形式:

 (
      {
         avgRtt = "1";                                // Average DNS resolution duration. Unit: milliseconds.
         cacheDnsNum = 0;                             // Number of cache hits.                       
         domain = "www.taobao.com"; // The domain name that you want to resolve.
         gobackLocaldnsNum = 0;                       // Number of times that DNS resolution is downgraded to the on-premises DNS server.
         localErro = 0;                               // Number of resolution failures on the on-premises DNS server.
         maxRtt = "60";                               // Maximum DNS resolution duration. Unit: milliseconds.
         noPermissionErro = 0;                        // Number of authentication failures.
         noResponseErro = 0;                          // Number of times that no response is returned.          
         requestPDnsNum = 1;                          // Number of recursive queries.
         sp = China Mobile;                                // Name of the ISP.
         successNum = 1;                              // Number of successful resolutions.
         timeoutErro = 0;                             // Number of network timeout errors.
         type = 28;                                   // If the value of the type parameter is 1, IPv4 addresses are used. If the value of the type parameter is 28, IPv6 addresses are used.
         urlParameterErro = 0;                        // Number of errors that are returned because the request parameter is invalid.
         urlPathErro = 0;                             // Number of errors that are returned because the URL is invalid.
      }
         ......
 );

6. 注意事項

  1. pdns-sdk-ios.frameworkフォルダは、iOS 9.0以降のみをサポートしています。

  2. HTTP経由でDNS解決を実行する場合は、Info.plistファイルで [アプリトランスポートのセキュリティ設定で任意のロードを許可]YESに設定する必要があります。

  3. Alibaba CloudパブリックDNSを使用してドメイン名をIPアドレスに解決した後、IPアドレスを使用してビジネスリクエストを送信できます。 解決されたドメイン名として、HTTPリクエストヘッダーのhostnameフィールドを指定する必要があります。

    例:

    // Set the ip parameter to an IP address to which a domain name is resolved.
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@", ip]];
    NSMutableURLRequest *mutableReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    // Set the host field to the domain name.
    [mutableReq setValue:@"Domain name" forHTTPHeaderField:@"host"];
  4. SDKを使用してドメイン名がマッピングされているIPアドレスを取得しない場合は、元のドメイン名のURLを使用してリクエストを送信する必要があります。 次のセクションでは、サンプルコードを示します。

    NSArray *array = [[DNSResolver share] getIpsByCacheWithDomain:@"Original domain name" andExpiredIPEnabled:YES];
    NSString *ip = array.firstObject;
    if (ip.length > 0) {
        // Replace the hostname in the URL with the IP address to send requests.
        
    }else{
        // Use the original URL to send requests.
    }
  5. 中間HTTPプロキシが存在する場合、クライアントはリクエストラインで絶対パスURLを使用します。 パブリックDNSが有効になっており、IP URLがアクセスに使用されている場合、中間プロキシはクライアントIP情報を実際のアクセスホスト情報としてターゲットサーバーに渡します。 その結果、ターゲットサーバは、真正のHOST情報なしではそのようなHTTP要求を処理することができない。 デバイスでネットワークプロキシが有効になっているかどうかを確認し、プロキシモードでのドメイン解決にパブリックDNSの使用を控えることを推奨します。

  6. デモプロジェクトは、Alibaba Cloud Public DNS SDKの使用方法を学ぶのに役立ちます。

    参考のためにデモプロジェクトをダウンロードできます。

7. SDK/APIについてのよくある質問

詳細については、「Alibaba CLoudパブリックDNS SDKおよびAPIに関するFAQ」をご参照ください。