#import <ifaddrs.h>
#import <arpa/inet.h>
// 獲取設(shè)備局域網(wǎng)地址
+(NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// 檢索當(dāng)前接口,在成功時,返回0
success = getifaddrs(&interfaces);
if (success == 0) {
// 循環(huán)鏈表的接口
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;
}
}
// 釋放內(nèi)存
freeifaddrs(interfaces);
return address;
}
//看了別人改了一下
//獲得手機(jī)IP地址
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"]; NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
//判斷返回字符串是否為所需數(shù)據(jù)
if ([ip hasPrefix:@"var returnCitySN = "]) { //刪除字符串多余字符串
NSRange range = NSMakeRange(0, 19);
[ip deleteCharactersInRange:range];
NSString * nowIp =[ip substringToIndex:ip.length-1]; //將字符串轉(zhuǎn)換成二進(jìn)制進(jìn)行Json解析
NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
return dict[@"cip"] ? dict[@"cip"] : @""; }
return @"";
//作者:陽光的味道_丁達(dá)爾
//鏈接:http://www.lxweimin.com/p/2a1a567bbb6e
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。