如何获取主机名/ IP地址的CNAME

时间:2017-06-23 06:49:18

标签: ios objective-c swift

我已经能够使用CFHost类从主机名获取IP地址,反之亦然,但无法从主机名获取CNAME。

任何人都知道如何解析主机名以获取其CNAME。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。希望它可以帮助有人寻找它:

+ (void) getCNAME {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    DNSServiceRef serviceRef;

    DNSServiceErrorType error;

    error = DNSServiceQueryRecord(&serviceRef, 0, 0, "apple.com", kDNSServiceType_CNAME,

                                  kDNSServiceClass_IN, queryCallback, NULL);

    if (error != kDNSServiceErr_NoError){

        NSLog(@"DNS Service error");

    }



    DNSServiceProcessResult(serviceRef);

    DNSServiceRefDeallocate(serviceRef);

});}

static void queryCallback(DNSServiceRef sdRef,

                      DNSServiceFlags flags,

                      uint32_t interfaceIndex,

                      DNSServiceErrorType errorCode,

                      const char *fullname,

                      uint16_t rrtype,

                      uint16_t rrclass,

                      uint16_t rdlen,

                      const void *rdata,

                      uint32_t ttl,

                      void *context) {



if (errorCode == kDNSServiceErr_NoError && rdlen > 1) {

    NSMutableData *txtData = [NSMutableData dataWithCapacity:rdlen];



    for (uint16_t i = 1; i < rdlen; i += 256) {

        [txtData appendBytes:rdata + i length:MIN(rdlen - i, 255)];

    }



    NSString *theTXT = [[NSString alloc] initWithBytes:txtData.bytes length:txtData.length encoding:NSASCIIStringEncoding];

    NSLog(@"CNAME: %@", theTXT);

}}