iOS上的LocalDNS异步域名解析方案

iOS上的LocalDNS异步域名解析方案

在iOS开发中, 我们很少需要自己去进行DNS解析, 网络请求都是有NSULRSession通过domain域名去进行网络请求, 但是在使用IP直连时, 我们需要直接ip直接请求HTTPS, 这样我们就有自己进行DNS解析的需求. 不论是使用LocalDNS还是使用HTTPDNS, 如何在iOS平台上实现, 并进行自由切换是一个需要研究的点.

LocalDNS的方法 -- getaddrinfo

针对LocalDNS方法, 最简单的方式是使用getaddrinfo, 这是一个 Unix 的API, 并且它与协议无关, 支持IPV4/IPV6, getaddrinfo() 函数能够处理名字到地址以及服务到端口这两种转换,返回的是一个struct addrinfo的结构体(列表)指针而不是一个地址清单。具体的方法如下:

/*
nodename:节点名可以是主机名,也可以是数字地址。(IPV4的10进点分,或是IPV6的16进制)
servname:包含十进制数的端口号或服务名如(ftp,http)
hints:是一个空指针或指向一个addrinfo结构的指针,由调用者填写关于它所想返回的信息类型的线索。
res:存放返回addrinfo结构链表的指针
*/
int getaddrinfo(
const char* nodename
const char* servname,
const struct addrinfo* hints,
struct addrinfo** res
);

void freeaddrinfo(struct addrinfo *ai); 

更加详细的解释还是man getaddrinfo去查看帮助手册吧. 里面有两个Demo

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

#define BUF_SIZE 500

int main(int argc, char *argv[])
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int sfd, s, j;
    size_t len;
    ssize_t nread;
    char buf[BUF_SIZE];
    struct sockaddr_in  *ipv4;
    struct sockaddr_in6 *ipv6;

    /* Obtain address(es) matching host/port */
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ALL;
    hints.ai_protocol = IPPROTO_TCP;

    s = getaddrinfo("www.google.com", "https", &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        switch (rp->ai_family) {
        case AF_INET:
            ipv4 = (struct sockaddr_in *)rp->ai_addr;
            inet_ntop(rp->ai_family, &ipv4->sin_addr, buf, sizeof(buf));
            break;
        case AF_INET6:
            ipv6 = (struct sockaddr_in6 *)rp->ai_addr;
            inet_ntop(rp->ai_family, &ipv6->sin6_addr, buf, sizeof(buf));
            break;
        }
        
        printf("[IPv%d]%s\n", rp->ai_family==AF_INET?4:6, buf);
    }

    /* No longer needed */
    freeaddrinfo(result);           

    exit(EXIT_SUCCESS);
}

上面的程序执行结果如下:

[IPv4]98.159.108.71
[IPv6]2001::1f0d:4817

如果查询www.baidu.com, 得到的结果是:

[IPv4]14.215.177.39
[IPv4]14.215.177.38

因此如果改造成OC的方法如下:

+(NSArray *)addressesForHost:(NSString *)host port:(NSNumber *)port error:(NSError**)outError
{
    struct addrinfo hints = {.ai_family=PF_UNSPEC;.ai_socktype=SOCK_STREAM;.ai_protocol=IPPROTO_TCP};
    struct addrinfo *res;
    int gai_error = getaddrinfo(host.UTF8String, port.stringValue.UTF8String, &hints, &res);
    if (gai_error) {
        if (outError) *outError = [NSError errorWithDomain:@"MyDomain" code:gai_error userInfo:@{NSLocalizedDescriptionKey:@(gai_strerror(gai_error))}];
        return nil;
    }
    NSMutableArray *addresses = [NSMutableArray array];
    struct addrinfo *ai = res;
    do {
        NSData *address = [NSData dataWithBytes:ai->ai_addr length:ai->ai_addrlen];
        [addresses addObject:address];
    } while (ai = ai->ai_next);
    freeaddrinfo(res);
    return [addresses copy];
}

+(NSString*)stringForAddress:(NSData*)addressData error:(NSError**)outError {
    char hbuf[NI_MAXHOST];
    int gai_error = getnameinfo(addressData.bytes, (socklen_t)addressData.length, hbuf, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
    if (gai_error) {
        if (outError) *outError = [NSError errorWithDomain:@"MyDomain" code:gai_error userInfo:@{NSLocalizedDescriptionKey:@(gai_strerror(gai_error))}];
        return nil;
    }
    return [NSString stringWithUTF8String:hbuf];
}

使用getaddrinfo方法是一个同步方法, 因此进行DNS lookup时候会阻塞当前线程!一般情况下DNS lookups can take anywhere from a few milliseconds up to ten seconds or longer. 这种不稳定的DNS耗时在我们实际开发中非常致命!

虽然我们可以用一个后台线程异步去进行DNS lookup, 但是这个方法block时候无法被代码取消!!!强制kill thread也可能导致内存泄露.

网上也有另外一个人做了测试https://github.com/FreeMind-LJ/DNSTest, 其中一个LocalDNS使用的res_query方法, 和getaddrinfo类似的.

ps1: IPV4中我们会使用gethostbyname()方法, 但是这个方法只能解析IPV4的结果.
ps2: 参考文章中也提到, Linux中有异步APIgetaddrinfo_a, 但是OSX和iOS中并没有实现!

LocalDNS -- CFNetwork

https://github.com/FreeMind-LJ/DNSTest中有使用CFHost使用同步方式进行DNS look的方式. 但是这些都不能满足我们对DNS服务进行异步获取,并支持取消操作的需求.

Apple官方有一个Demo CFHostSample, 内部实现了使用CFHost实现asynchronous DNS name-to-address and address-to-name queries方法, 参考官方Demo

另外有一篇参考文章使用了DNSResolver进行后台解析,

#import <arpa/inet.h>
#import <Foundation/Foundation.h>
@interface DNSResolver : NSObject
    @property NSString *hostname;
    @property NSArray *addresses;
    @property NSError *error;
    @property BOOL shouldCancel, done;
    -(BOOL)lookup;
@end

@implementation DNSResolver {
    BOOL done;
}

-(BOOL)lookup {
    // sanity check
    if (!self.hostname) {
        self.error = [NSError errorWithDomain:@"MyDomain" code:1 userInfo:@{NSLocalizedDescriptionKey:@"No hostname provided."}];
        return NO;
    }
    NSArray* urlComponents = [self.hostname componentsSeparatedByString:@":"];
    // set up the CFHost object
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)urlComponents[0]);
    CFHostClientContext ctx = {.info = (__bridge void*)self};
    CFHostSetClient(host, DNSResolverHostClientCallback, &ctx);
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    CFHostScheduleWithRunLoop(host, runloop, CFSTR("DNSResolverRunLoopMode"));
    // start the name resolution
    CFStreamError error;
    Boolean didStart = CFHostStartInfoResolution(host, kCFHostAddresses, &error);
    if (!didStart) {
        self.error = [NSError errorWithDomain:@"MyDomain" code:1 userInfo:@{NSLocalizedDescriptionKey:@"CFHostStartInfoResolution failed."}];
        return NO;
    }
    // run the run loop for 50ms at a time, always checking if we should cancel
    while(!done) {
        CFRunLoopRunInMode(CFSTR("DNSResolverRunLoopMode"), 0.05, true);
    }

    if (!self.error) {
        Boolean hasBeenResolved;
        CFArrayRef addressArray = CFHostGetAddressing(host, &hasBeenResolved);
        if (hasBeenResolved) {
            NSMutableArray* tmp = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(addressArray)];
            for(int i = 0; i < CFArrayGetCount(addressArray); i++){
                struct sockaddr_in* remoteAddr;
                CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex(addressArray, i);
                remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData);
                
                if(remoteAddr != NULL) {
                    NSString *strDNS =[NSString stringWithCString:inet_ntoa(remoteAddr->sin_addr) encoding:NSASCIIStringEncoding];
                    [tmp addObject:[[strDNS stringByAppendingString:@":"] stringByAppendingString:urlComponents[1]]];
                }
            }
            self.addresses = [tmp copy];
        } else {
            self.error = [NSError errorWithDomain:@"MyDomain" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Name look up failed"}];
        }
    }
    // clean up the CFHost object
    CFHostSetClient(host, NULL, NULL);
    CFHostUnscheduleFromRunLoop(host, runloop, CFSTR("DNSResolverRunLoopMode"));
    CFRelease(host);
    return self.error ? NO : YES;
}

void DNSResolverHostClientCallback ( CFHostRef theHost, CFHostInfoType typeInfo, const CFStreamError *error, void *info) {
    DNSResolver *self = (__bridge DNSResolver*)info;
    if (error->domain || error->error) self.error = [NSError errorWithDomain:@"MyDomain" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Name look up failed"}];
    self->done = YES;
}

@end

在使用异步解析时:

dispatch_async(dispatch_get_main_queue(), ^ {
    self->ipArray = [[NSMutableArray alloc] init];
    NSArray* urls = [[Config sharedInstance] getParameter:@"verification_url"];
    DNSResolver* resolver;
    for (NSString* url in urls) {
        resolver = [[DNSResolver alloc] init];
        resolver.hostname = url;
        if (![resolver lookup]) {
            DLog("%@", resolver.error);
            continue;
        }
        [self->ipArray addObjectsFromArray:resolver.addresses];
    }
    [self->ipArray shuffle];
    self->ipEnumarator = [self->ipArray objectEnumerator];
    self->timeoutLen = ([[[Config sharedInstance] getParameter:@"con_timeout_1"] intValue] / 1000.0);
    [self handleConnection];
});

这样就能异步进行 DNS lookup, 并且可以主动掉cancel, 或者在出错时停止服务!!!

另外一个实现可以参考: https://github.com/sebk/DNSResolver

参考

https://eggerapps.at/blog/2014/hostname-lookups.html

https://github.com/sebk/DNSResolver

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容