【发布时间】:2010-09-20 14:27:56
【问题描述】:
如何查询iPhone当前的IP地址?
【问题讨论】:
标签: iphone networking
如何查询iPhone当前的IP地址?
【问题讨论】:
标签: iphone networking
如果您想要external IP 地址(用于从本地网络外部连接的地址),您需要查询外部网络上的服务器。快速搜索得到以下结果:http://checkip.dyndns.org、http://www.whatismyip.com。使用例如加载页面非常简单。
[NSData dataWithContentsOfURL:url]
并进行一些字符串操作以检索 IP 地址。
如果您想要内部 IP 地址(例如由 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;
}
【讨论】:
你可以尝试使用类似这个服务: Whatismyip 并捕获字符串 :)
感谢 Erica Sadun 的 iPhone Developer's Cookbok,第 2 版,第 555 页。
【讨论】: