iOS 根据域名获取IP

根据域名获取IP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <netdb.h>
#include <sys/socket.h>
//根据域名获取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;
}