您的位置:首页 > 移动开发 > IOS开发

根据域名动态获取IP地址(iOS)

2017-07-07 14:16 609 查看
需要导入以下头文件

#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>


具体方法为

- (NSString*)getIPWithHostName:(const NSString*)hostName {

const char *hostN= [hostName UTF8String];
struct hostent* phot;
@try {
phot = gethostbyname(hostN);
if (phot == nil) {
return nil;
}
}
@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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: