#import <ifaddrs.h>
#import <arpa/inet.h>
// 获取设备局域网地址
+(NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// 检索当前接口,在成功时,返回0
success = getifaddrs(&interfaces);
if (success == 0) {
// 循环链表的接口
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// 检查接口是否en0 wifi连接在iPhone上
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// 得到NSString从C字符串
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// 释放内存
freeifaddrs(interfaces);
return address;
}
//看了别人改了一下
//获得手机IP地址
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"]; NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
//判断返回字符串是否为所需数据
if ([ip hasPrefix:@"var returnCitySN = "]) { //删除字符串多余字符串
NSRange range = NSMakeRange(0, 19);
[ip deleteCharactersInRange:range];
NSString * nowIp =[ip substringToIndex:ip.length-1]; //将字符串转换成二进制进行Json解析
NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
return dict[@"cip"] ? dict[@"cip"] : @""; }
return @"";
//作者:阳光的味道_丁达尔
//链接:https://www.jianshu.com/p/2a1a567bbb6e