背景
最近在做iOS的DNS解析,顺便研究了下iOS端本地的DNS解析方式(localDNS),也就是不依赖Http请求,而是用原始的API进行解析,虽然有HttpDNS但是考虑到成本、第三方服务稳定性的问题,LocalDNS仍然是一个很重要的部分,在iOS系统下,localDNS的解析方式有三种,下面主要对三种方式进行下利弊分析及简单的原理介绍。
方式一
这个也是我一开始在项目中使用的方式。
1:struct hostent *gethostbyname(const char *);
2:struct hostent *gethostbyname2(const char *, int);
两个函数作用完全一样,返回值一样,但是第一个只能用于IPV4的网络环境,而第二个则IPV4和IPV6都可使用,可以通过第二个参数传入当前的网络环境。
使用方式:
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
char *ptr, **pptr;
struct hostent *hptr;
char str[32];
ptr = "www.meitu.com";
NSMutableArray * ips = [NSMutableArray array];
if((hptr = gethostbyname(ptr)) == NULL)
{
return;
}
for(pptr=hptr->h_addr_list; *pptr!=NULL; pptr++) {
NSString * ipStr = [NSString stringWithCString:inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)) encoding:NSUTF8StringEncoding];
[ips addObject:ipStr?:@""];
}
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"22222 === ip === %@ === time cost: %0.3fs", ips,end - start);
使用gethostbyname方法后会得到一个struct,也就是上文的struct hostent *hptr:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses from