我该如何查询iPhone的当前IP地址?
如果您需要获取外部IP地址(即从本地网络之外连接时使用的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;
}