iOS 域名解析

时间:2023-03-08 16:53:59

如何在iOS下进行域名的解析?

/**

*  域名解析ip

*

*  @param hostName 域名

*

*  @return ip

*/

+(NSString *) getIPWithHostName:(const NSString *)hostName

{

const char *hostN= [hostName UTF8String];

struct hostent* phot;

@try {

phot = gethostbyname(hostN);

}

@catch (NSException *exception) {

return nil;

}

struct in_addr ip_addr;

memcpy(&ip_addr, phot->h_addr_list[0], 4);

char ip[20] = {0};

inet_ntop(AF_INET, &ip_addr, ip, sizeof(ip));

NSString* strIPAddress = [NSString stringWithUTF8String:ip];

return strIPAddress;

}

NSString *ip = [DomainNameResolution getIPWithHostName:@"www.baidu.com"];

NSLog(@"%@",ip);

打印结果:

2016-08-21 10:31:57.653 DomainNameResolution[1284:37374] 14.215.177.38

Demo地址:https://github.com/JnKindle/DomainNameResolution