Kru*_*lur 13
如果需要外部 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;
}
Run Code Online (Sandbox Code Playgroud)