在APP中,有时候需要对用户设备的网络状态进行实时监控,让用户了解自己的网络状态,根据用户的网络状态进行智能处理,节省用户流量,提高用户体验.
检测网络状态有多重方法,最常见的是 苹果官方提供了一个叫Reachability和AFNetworing检测网络(网上很多二者的用法,自行百度).但是,细心的朋友们不知道有没有发现,手机的状态栏上一般都会有当前网络状态的显示,因为状态栏是系统级别的View,是受苹果保护的,不可以随便更改,不可以随便遮挡住。如果违反这些苹果的规范,那么APP将有可能上不了架。所以一般很少对状态栏操作,但是状态栏并非不能操作,下面演示下状态栏的简单用法.
一、操作状态栏的样式
ios开发中对状态栏的操作比较少,开发中最常见的对状态栏的操作就是设置状态栏的样式,比如:
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
(此样式的状态栏中的字为白色,所以用在导航栏为深色的情况下,例如黑色或者红色的导航栏)
默认的状态栏样式是:
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
(此样式的状态栏中的字为黑色色,所以用在导航栏为浅色色的情况下,比如白色的导航栏)
如果你设置了,发现状态栏没反应,那么你要去info.plist中加一个key,这个key为View controller-based status bar appearance,对应的value为NO。这样每个vc中就可以随便设置状态栏的样式了。
View controller-based status bar appearance :NO
二、操作状态栏的背景颜色
我们可以拿到状态栏这个UIView对象,可以改变状态栏的颜色,背景颜色(backgroundColor)、大小位置(frame)等等。
- (void)viewDidLoad {
[super viewDidLoad];
UIView *bg = [self statusBarView];
bg.backgroundColor = [UIColor redColor];
bg.frame = CGRectMake(0, 100, self.view.frame.size.width, 60);
}
- (UIView*)statusBarView;
{
UIView *statusBar = nil;
NSData *data = [NSData dataWithBytes:(unsigned char []){0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0x61, 0x72} length:9];
NSString *key = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
id object = [UIApplication sharedApplication];
if ([object respondsToSelector:NSSelectorFromString(key)]) statusBar = [object valueForKey:key];
return statusBar;
}
以上是状态栏的简单操作和设置,一般情况下也用不到,因为真是项目开发中不会这样随意改变状态栏的高度及颜色,但是状态栏上的这些信息一般都还是有用的.接着看代码
三、操作状态栏,得到网络类型
定义一个NetworkTools工具类,用来获取网络类型及状态,要知道最终获取到状态栏上的运营商名称要经过一层层的提取,下面就开始一层层分析
//1.状态栏是由当前app控制的,首先获取当前app
UIApplication *app = [UIApplication sharedApplication];
id statusBar = [app valueForKeyPath:@"statusBar"];
// 遍历状态栏的所有成员
unsigned int outCount =0;
Ivar *ivars = class_copyIvarList([statusBar class], &outCount);
for (int i =0; i < outCount; i++) {
Ivar ivar = ivars[i];
printf("%s\n",ivar_getName(ivar));
}
打印结果:
_statusBarServer
_inProcessProvider
_showsForeground
_backgroundView
_foregroundView
_doubleHeightLabel
_doubleHeightLabelContainer
_currentDoubleHeightText
_currentRawData
_interruptedAnimationCompositeViews
_newStyleBackgroundView
_newStyleForegroundView
_slidingStatusBar
_requestedStyle
_styleOverrides
_styleAttributes
_orientation
_hidden
_suppressesHiddenSideEffects
_foreground
_registered
_waitingOnCallbackAfterChangingStyleOverridesLocally
_suppressGlow
_translucentBackgroundAlpha
_showOnlyCenterItems
_foregroundViewShouldIgnoreStatusBarDataDuringAnimation
_localDataOverrides
_tintColor
_lastUsedBackgroundColor
_nextTintTransition
_overrideHeight
_disableRasterizationReasons
_persistentAnimationsEnabled
_simulatesLegacyAppearance
_serverUpdatesDisabled
_timeHidden
_homeItemsDisabled
_statusBarWindow
_styleDelegate
_dockDataProvider
__transitionCoordinator
_foregroundColor
_legibilityStyle
- 进入foregroundView元素并遍历其所有子元素
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
for (id child in children) {
NSLog(@"%@", [child class]);
}
打印结果:
UIStatusBarSignalStrengthItemView
UIStatusBarServiceItemView
UIStatusBarDataNetworkItemView
UIStatusBarBatteryItemView
UIStatusBarBluetoothItemView
UIStatusBarIndicatorItemView
UIStatusBarTimeItemView
- 进入UIStatusBarServiceItemView/UIStatusBarDataNetworkItemView/UIStatusBarSignalStrengthItemView元素并遍历其所有子元素
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")]) {
unsigned int outCount =0;
Ivar *ivars = class_copyIvarList([child class], &outCount);
for (int i =0; i < outCount; i++) {
Ivar ivar = ivars[i];
printf("%s\n",ivar_getName(ivar));
}
}
}
打印结果:
_serviceString
_crossfadeString
_crossfadeStep
_maxWidth
_serviceWidth
_crossfadeWidth
_contentType
_loopingNecessaryForString
_loopNowIfNecessary
_loopingNow
_letterSpacing
- 通过serviceString获取运营商名称
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")]) {
// 遍历当前状态栏的所有属性,找到关于状态栏的
unsigned int outCount =0;
Ivar *ivars = class_copyIvarList([child class], &outCount);
for (int i =0; i < outCount; i++) {
Ivar ivar = ivars[i];
printf("%s\n",ivar_getName(ivar));
}
//1._serviceString
id type = [child valueForKeyPath:@"serviceString"];
NSLog(@"_serviceString: %@", type);
}
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarBatteryItemView")]) {
unsigned int outCount =0;
Ivar *ivars = class_copyIvarList([child class], &outCount);
for (int i =0; i < outCount; i++) {
Ivar ivar = ivars[i];
printf("%s\n",ivar_getName(ivar));
}
id cachedCapacity = [child valueForKeyPath:@"cachedCapacity"];
NSLog(@"cachedCapacity: %@", cachedCapacity);
}
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取网络类型
NSInteger netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
NSLog(@"netType: %ld", netType);
//wifi信号强度
int signalStrength = [[child valueForKeyPath:@"wifiStrengthBars"]intValue];
NSLog(@"netType: %d", signalStrength);
}
}
打印结果:
UIStatusBarDataNetworkItemView结果:
_dataNetworkType
_wifiStrengthRaw
_wifiStrengthBars
_wifiLinkWarning
_enableRSSI
_showRSSI
UIStatusBarBatteryItemView结果:
_capacity
_state
_batterySaverModeActive
_accessoryView
_cachedImageHasAccessoryImage
_cachedCapacity
_cachedImageSet
_cachedBatteryStyle
好了,至此我们已经拿到了网络状态,遍历UIStatusBar还可以获取到其他的有用信息,下面是一些常用的信息获取方式,封装了一个"NetworkTools"工具类
NetworkTools.h文件
//
// NetworkTools.h
// Demo
//
// Created by Allison on 2017/7/13.
// Copyright © 2017年 Allison. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NetworkTools : NSObject
// 获取设备uuid
+ (NSString*)getUUID;
// 设备mac 地址
+ (NSString *)macaddress;
// Version
+ (NSString *)getVersion;
// SIM卡所属的运营商(公司)
+(NSString *)serviceCompany;
+(NSDictionary *)getDinfo;
@end
NetworkTools.m文件
//
// NetworkTools.m
// Demo
//
// Created by Allison on 2017/7/13.
// Copyright © 2017年 Allison. All rights reserved.
//
#import "NetworkTools.h"
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>
#import <UIKit/UIKit.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <sys/stat.h> //真机必须导入这个头文件
/*
* Top-level identifiers
*/
#define CTL_NET 4 /* network, see socket.h */
#define AF_ROUTE 17 /* Internal Routing Protocol */
#define AF_LINK 18 /* Link layer interface */
#define NET_RT_IFLIST2 6 /* interface list with addresses */
#define NET_RT_IFLIST 3 /* survey interface list */
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
//获取屏幕宽度
#define screenWide [UIScreen mainScreen].bounds.size.width
//获取屏幕高度
#define screenHeight [UIScreen mainScreen].bounds.size.height
@implementation NetworkTools
// 获取设备uuid
+ (NSString*)getUUID {
CFUUIDRef puuid = CFUUIDCreate( nil );
CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
return result;
}
// 设备mac 地址
+ (NSString *)macaddress
{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error/n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1/n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!/n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
NSLog(@"outString:%@", outstring);
free(buf);
return [outstring uppercaseString];
}
// Version
+ (NSString *)getVersion {
NSString *string = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:string];
NSString *version = [dic objectForKey:@"CFBundleVersion"];
return version;
}
///SIM卡所属的运营商(公司)
+(NSString *)serviceCompany{
NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
for (id info in infoArray)
{
if ([info isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")])
{
NSString *serviceString = [info valueForKeyPath:@"serviceString"];
NSLog(@"公司为:%@",serviceString);
return serviceString;
}
}
return @"";
}
+ (NSDictionary *)getDinfo {
NSString *mac = [self macaddress];
NSString *udid = [self getUUID];
NSString *ip = [self ipAddressIsV4:YES];
NSString *p = [self getDeviceInfo];
NSString *jb = [NSString stringWithFormat:@"%i",[self jailbroken]];
NSString *rw = [NSString stringWithFormat:@"%f",screenWide];
NSString *rh = [NSString stringWithFormat:@"%f",screenHeight];
NSString *o = [self chinaMobileModel];
NSString *m = [self deviceName];
NSString *osv = [self getSystemVersion];
NSString *cv = [NSString stringWithFormat:@"%ld",[self version]];
NSString *n = [self getNetWorkStates];
NSDictionary *dinfo = @{
@"os":@"i",
@"osv": osv,
@"osvc":@"17",
@"udid": udid,
@"ip":ip,
@"p":p,
@"jb":jb,
@"rw":rw,
@"rh":rh,
@"o":o,
@"m":m,
@"cv":cv,
@"cvc":@"14",
@"mac": mac,
@"n":n,
@"phone":@"",
@"imsi":@"",
@"imei":@""
};
return dinfo;
}
// 判断当前网络连接状态
+(NSString *)getNetWorkStates{
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
NSString *state = [[NSString alloc]init];
int netType = 0;
//获取到网络返回码
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取到状态栏
netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
NSLog(@"netType:%d",netType);
switch (netType) {
case 0:
// state = @"无网络"; // 5
state = @"5";
//无网模式
break;
case 1:
// state = @"2G"; // 1
state = @"1";
break;
case 2:
// state = @"3G"; // 2
state = @"3";
break;
case 3:
// state = @"4G"; //3
state = @"4";
break;
case 5:
// state = @"WIFI"; //5
state = @"5";
break;
default:
break;
}
}
}
//根据状态选择
return state;
}
+ (NSString *)getSystemVersion {
UIDevice *device = [[UIDevice alloc] init];
NSString *systemVersion = device.systemVersion;
return systemVersion;
}
// ip 地址
+ (NSString *)ipAddressIsV4:(BOOL)v4
{
NSArray *searchArray = v4 ?
@[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self addressInfo];
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
if(address) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
// 设备信息 产品名称
+ (NSString *)getDeviceInfo {
UIDevice *device = [[UIDevice alloc] init];
NSString *name = device.name; //获取设备所有者的名称
NSString *model = device.name; //获取设备的类别
NSString *type = device.localizedModel; //获取本地化版本
NSString *systemName = device.systemName; //获取当前运行的系统
NSString *systemVersion = device.systemVersion;//获取当前系统的版本
NSLog(@"-----name : %@,model : %@,type : %@,systemName :%@,systemVersion %@",name,model,type,systemName,systemVersion);
return model;
}
// 是否越狱
+ (BOOL)jailbroken
{
#if !TARGET_IPHONE_SIMULATOR
//Apps and System check list
BOOL isDirectory;
NSFileManager *defaultManager = [NSFileManager defaultManager];
if ([defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Cyd", @"ia.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"bla", @"ckra1n.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Fake", @"Carrier.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Ic", @"y.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Inte", @"lliScreen.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"MxT", @"ube.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Roc", @"kApp.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"SBSet", @"ttings.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Wint", @"erBoard.a", @"pp"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/l", @"ib/a", @"pt/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/l", @"ib/c", @"ydia/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/mobile", @"Library/SBSettings", @"Themes/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/t", @"mp/cyd", @"ia.log"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/s", @"tash/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/cy", @"dia/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"us", @"r/b",@"in", @"s", @"shd"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"us", @"r/sb",@"in", @"s", @"shd"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/cy", @"dia/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/sftp-", @"server"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@",@"/Syste",@"tem/Lib",@"rary/Lau",@"nchDae",@"mons/com.ike",@"y.bbot.plist"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@%@",@"/Sy",@"stem/Lib",@"rary/Laun",@"chDae",@"mons/com.saur",@"ik.Cy",@"@dia.Star",@"tup.plist"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/Libr",@"ary/Mo",@"bileSubstra",@"te/MobileSubs",@"trate.dylib"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/va",@"r/c",@"ach",@"e/a",@"pt/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"ib",@"/apt/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"ib/c",@"ydia/"] isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"og/s",@"yslog"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/bi",@"n/b",@"ash"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/b",@"in/",@"sh"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/et",@"c/a",@"pt/"]isDirectory:&isDirectory]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/etc/s",@"sh/s",@"shd_config"]]
|| [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/us",@"r/li",@"bexe",@"c/ssh-k",@"eysign"]])
{
return YES;
}
// SandBox Integrity Check
int pid = fork(); //返回值:子进程返回0,父进程中返回子进程ID,出错则返回-1
if(!pid){
exit(0);
}
if(pid>=0)
{
return YES;
}
//Symbolic link verification
struct stat s;
if(lstat("/Applications", &s) || lstat("/var/stash/Library/Ringtones", &s) || lstat("/var/stash/Library/Wallpaper", &s)
|| lstat("/var/stash/usr/include", &s) || lstat("/var/stash/usr/libexec", &s) || lstat("/var/stash/usr/share", &s)
|| lstat("/var/stash/usr/arm-apple-darwin9", &s))
{
if(s.st_mode & S_IFLNK){
return YES;
}
}
//Try to write file in private
NSError *error;
[[NSString stringWithFormat:@"Jailbreak test string"] writeToFile:@"/private/test_jb.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(nil==error){
//Writed
return YES;
} else {
[defaultManager removeItemAtPath:@"/private/test_jb.txt" error:nil];
}
#endif
return NO;
}
+ (NSDictionary *)addressInfo
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) || (interface->ifa_flags & IFF_LOOPBACK)) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
char addrBuf[INET6_ADDRSTRLEN];
if(inet_ntop(addr->sin_family, &addr->sin_addr, addrBuf, sizeof(addrBuf))) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, addr->sin_family == AF_INET ? IP_ADDR_IPv4 : IP_ADDR_IPv6];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
// 运营商
+ (NSString *)chinaMobileModel
{
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [info subscriberCellularProvider];
if (carrier == nil) {
// return @"不识别";
return @"0";
}
NSString *code = [carrier mobileNetworkCode];
if (code == nil) {
// return @"不识别";
return @"0";
}
if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"07"])
{
// return @"移动";
return @"1";
}else if ([code isEqualToString:@"01"] || [code isEqualToString:@"06"])
{
// return @"联通";
return @"2";
}else if ([code isEqualToString:@"03"] || [code isEqualToString:@"05"])
{
// return @"电信";
return @"3";
}else if ([code isEqualToString:@"20"])
{
return @"铁通";
}
return @"不识别";
}
+ (NSString *)deviceModel
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *model = malloc(size);
sysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
free(model);
return deviceModel;
}
// 机型信息
+ (NSString *)deviceName
{
NSString *platform = [self deviceModel];
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (GSM)";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (CDMA)";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (CDMA)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5C";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5C";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5S";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5S";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (CDMA)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (CDMA)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (CDMA)";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (GSM)";
if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air (CDMA)";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini Retina (WiFi)";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini Retina (CDMA)";
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
return platform;
}
@end
用法:
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *infoDic = [NetworkTools getDinfo];
NSLog(@"%@", infoDic);
}
输出结果
{
cv = 0;
cvc = 14;
imei = "";
imsi = "";
ip = "192.168.0.110";
jb = 0;
m = "iPhone 6S";
mac = "00:00:00:00:00:02";
n = 5;
o = 1;
os = i;
osv = "10.3.2";
osvc = 17;
p = "\U738b\U59e3\U59e3\U7684 iPhone";
phone = "";
rh = "568.000000";
rw = "320.000000";
udid = "AAAAAAAA-AAAA-AAAA-AAAA-D215092D9489";
}
最后附上下载地址:Demo.