如果你想要externalIP地址(用于从本地网络外部连接的IP地址),您需要查询外部网络上的服务器。快速搜索后得到以下结果:http://checkip.dyndns.org http://checkip.dyndns.org, http://www.whatismyip.com http://www.whatismyip.com。使用例如加载页面非常简单
[NSData dataWithContentsOfURL:url]
并进行一些字符串操作来检索 IP 地址。
如果你想要internalIP 地址(例如通过 DHCP 分配给您的设备的地址),您通常可以做的是解析设备的主机名,即
/*
Returns the local IP, or NULL on failure.
*/
const char* GetLocalIP() {
char buf[256];
if(gethostname(buf,sizeof(buf)))
return NULL;
struct hostent* he = gethostbyname(buf);
if(!he)
return NULL;
for(int i=0; he->h_addr_list[i]; i++) {
char* ip = inet_ntoa(*(struct in_addr*)he->h_addr_list[i]);
if(ip != (char*)-1) return ip;
}
return NULL;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)