ios 开发之获取手机的外网IP和内网IP

来源:互联网 发布:河北大学网络教育招生 编辑:程序博客网 时间:2024/06/06 20:41

一、获取手机的内网IP

​- (NSString *) ipaddr

{ NSString *address = nil; s

truct ifaddrs *interfaces = NULL;

struct ifaddrs *temp_addr = NULL;

int success = 0; success = getifaddrs(&interfaces);

if (success == 0) {

temp_addr = interfaces;

while (temp_addr != NULL)

{ if (temp_addr->ifa_addr->sa_family == AF_INET)

{ if (strcmp(temp_addr->ifa_name, “en0”) == 0)

{ address = [NSString

stringWithUTF8String:

inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)]; }

} temp_addr = temp_addr->ifa_next; } }

// Free memory freeifaddrs(interfaces);

//NSLog(@”%@”,address); return address;

}

二、获取手机的外网IP 目前移动设备能获取外网IP只能通过访问才能对其获得,提供一个比较简单的方法 :就三行代码

NSError *error; NSURL *ipURL = [NSURL URLWithString:@”http://ifconfig.me/ip“]; NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];

参考链接:​http://blog.csdn.net/fightper/article/details/6858881​开源代码:http://code4app.com/ios/What-is-my-IP/530acdb9cb7e84b2578b47e4​​​​

0 0
原创粉丝点击