iOS获取设备内存、IP、系统型号、APP版本号、电池电量等
2017-07-20 本文已影响27人
疯得得
在下只是搬运工,对网络上的方法进行了整理写进了一个文件,看得上的就拿去用吧。
//
// SystemRelated.h
// CustomProject
//
// Created by FengYiHao on 2017/7/19.
// Copyright © 2017年 FengYiHao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SystemRelated : NSObject
/** getDeviceInfo
*
* TODO:获取设备信息包括手机型号IP等等
*
*/
+ (NSString *)getDeviceInfo;
/** getMemoryAbout
*
* TODO:获取设备内存相信息
*
*/
+ (NSString *)getMemoryAbout;
/** getUsedMemory
*
* TODO:获取已使用内存大小
*
*/
+ (double)getUsedMemory;
/** getFreeMemory
*
* TODO:获取空闲内存大小
*
*/
+ (double)getFreeMemory;
/** getBatteryLevel
*
* 获取电池电量
*
*/
+ (double)getBatteryLevel;
/** getMacAddress
*
* TODO:获取设备Mac地址
*
*/
+ (NSString *)getMacAddress;
/** appVersion
*
* TODO:获取App版本
*
*/
+ (NSString *)appVersion;
/** iphoneSystemName
*
* TODO:获取手机系统
*
*/
+ (NSString *)iphoneSystemName;
/** iphoneSystemVersion
*
* TODO:手机系统版本
*
*/
+ (NSString *)iphoneSystemVersion;
/** getDeviceName
*
* TODO:获取设备型号然后手动转化为对应名称
*
*/
+ (NSString *)getDeviceName;
/** getUUID
*
* TODO:获取设备惟一标示符
*
*/
- (NSString *)getUUID;
/** getIPAddress
*
* TODO:获取IP
*
*/
+ (NSString *)getIPAddress:(BOOL)preferIPv4;
/** getIPAddressWithWAN
*
* TODO:获取外网IP
*
*/
+ (NSString *)getIPAddressWithWAN;
/** isValidatIP
*
* TODO:IP验证
*
*/
+ (BOOL)isValidatIP:(NSString *)ipAddress;
/** getIPAddresses
*
* TODO:获取IP相关信息
*
*/
+ (NSDictionary *)getIPAddresses;
@end
//
// SystemRelated.m
// CustomProject
//
// Created by FengYiHao on 2017/7/19.
// Copyright © 2017年 FengYiHao. All rights reserved.
//
#import "SystemRelated.h"
#import <mach/mach.h>
#import <sys/utsname.h>
#import <AdSupport/AdSupport.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if_dl.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
@implementation SystemRelated
+ (NSString *)getMemoryAbout{
vm_statistics_data_t vmstat;
return [NSString stringWithFormat:@"\nfree(空闲): %0.1fM\nactive(已使用,可分页): %0.1fM\ninactive(不活跃): %0.1fM\nwire(已使用,不可分页): %0.1fM\nzero fill: %0.1f\nreactivations: %0.1f\npageins: %0.1f\npageouts: %0.1f\nfaults:%0.1f\ncow_faults: %0.1f\nlookups: %0.1f\nhits: %0.1f\n注:在iOS中,只有在磁盘上静态存在的才能被分页,例如文件的内存映射,而动态分配的内存是不能被分页的",
vmstat.free_count * vm_page_size/1024.0/1024.0,
vmstat.active_count * vm_page_size/1024.0/1024.0,
vmstat.inactive_count * vm_page_size/1024.0/1024.0,
vmstat.wire_count * vm_page_size/1024.0/1024.0,
vmstat.zero_fill_count * vm_page_size,
vmstat.reactivations * vm_page_size,
vmstat.pageins * vm_page_size,
vmstat.pageouts * vm_page_size,
vmstat.faults,
vmstat.cow_faults,
vmstat.lookups,
vmstat.hits];
}
/** getUsedMemory
*
* 获取已使用内存大小
*
*/
+ (double)getUsedMemory{
task_basic_info_data_t info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),TASK_BASIC_INFO,(task_info_t) &info, &size);
return (kerr == KERN_SUCCESS) ? info.resident_size/1024/1024 : 0;
}
/** getFreeMemory
*
* 获取空余内存大小
*
*/
+ (double)getFreeMemory{
mach_port_t host = mach_host_self();
mach_msg_type_number_t size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t pagesize;
vm_statistics_data_t vmstat;
host_page_size(host, &pagesize);
host_statistics(host, HOST_VM_INFO, (host_info_t) &vmstat, &size);
return vmstat.free_count * pagesize/1024.0/1024.0;
}
/** getBatteryLevel
*
* 获取电池电量
*
*/
+ (double)getBatteryLevel{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
double batteryLevel = (float)[myDevice batteryLevel];
return batteryLevel;
}
/** appVersion
*
* 获取App版本
*
*/
+ (NSString *)appVersion{
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow((__bridge CFTypeRef)(infoDictionary));
return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}
/** iphoneSystemName
*
* 获取手机系统
*
*/
+ (NSString *)iphoneSystemName{
return [[UIDevice currentDevice] systemName];
}
/** iphoneSystemVersion
*
* 手机系统版本
*
*/
+ (NSString *)iphoneSystemVersion{
return [[UIDevice currentDevice] systemVersion];
}
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to mlamb.
+ (NSString *)getMacAddress{
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)];
free(buf);
return [outstring uppercaseString];
}
/** iphoneType
*
* 获取设备型号然后手动转化为对应名称
*
*/
+ (NSString *)getDeviceName
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
if ([deviceString isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([deviceString isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([deviceString isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([deviceString isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([deviceString isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([deviceString isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([deviceString isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([deviceString isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([deviceString isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
// 日行两款手机型号均为日本独占,可能使用索尼FeliCa支付方案而不是苹果支付
if ([deviceString isEqualToString:@"iPhone9,1"]) return @"国行、日版、港行iPhone 7";
if ([deviceString isEqualToString:@"iPhone9,2"]) return @"港行、国行iPhone 7 Plus";
if ([deviceString isEqualToString:@"iPhone9,3"]) return @"美版、台版iPhone 7";
if ([deviceString isEqualToString:@"iPhone9,4"]) return @"美版、台版iPhone 7 Plus";
if ([deviceString isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([deviceString isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([deviceString isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([deviceString isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([deviceString isEqualToString:@"iPod5,1"]) return @"iPod Touch (5 Gen)";
if ([deviceString isEqualToString:@"iPad1,1"]) return @"iPad";
if ([deviceString isEqualToString:@"iPad1,2"]) return @"iPad 3G";
if ([deviceString isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([deviceString isEqualToString:@"iPad2,2"]) return @"iPad 2";
if ([deviceString isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([deviceString isEqualToString:@"iPad2,4"]) return @"iPad 2";
if ([deviceString isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([deviceString isEqualToString:@"iPad2,6"]) return @"iPad Mini";
if ([deviceString isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([deviceString isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad3,3"]) return @"iPad 3";
if ([deviceString isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([deviceString isEqualToString:@"iPad3,5"]) return @"iPad 4";
if ([deviceString isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([deviceString isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
if ([deviceString isEqualToString:@"iPad4,4"]) return @"iPad Mini 2 (WiFi)";
if ([deviceString isEqualToString:@"iPad4,5"]) return @"iPad Mini 2 (Cellular)";
if ([deviceString isEqualToString:@"iPad4,6"]) return @"iPad Mini 2";
if ([deviceString isEqualToString:@"iPad4,7"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad4,8"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad4,9"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad5,1"]) return @"iPad Mini 4 (WiFi)";
if ([deviceString isEqualToString:@"iPad5,2"]) return @"iPad Mini 4 (LTE)";
if ([deviceString isEqualToString:@"iPad5,3"]) return @"iPad Air 2";
if ([deviceString isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
if ([deviceString isEqualToString:@"iPad6,3"]) return @"iPad Pro 9.7";
if ([deviceString isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7";
if ([deviceString isEqualToString:@"iPad6,7"]) return @"iPad Pro 12.9";
if ([deviceString isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9";
if ([deviceString isEqualToString:@"i386"]) return @"Simulator";
if ([deviceString isEqualToString:@"x86_64"]) return @"Simulator";
return deviceString;
}
/** getDeviceIPAddresses
*
* 获取设备IP
*
*/
+ (NSString *)getDeviceIPAddresses {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
NSMutableArray *ips = [NSMutableArray array];
int BUFFERSIZE = 4096;
struct ifconf ifc;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifreq *ifr, ifrcopy;
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
ifr = (struct ifreq *)ptr;
int len = sizeof(struct sockaddr);
if (ifr->ifr_addr.sa_len > len) {
len = ifr->ifr_addr.sa_len;
}
ptr += sizeof(ifr->ifr_name) + len;
if (ifr->ifr_addr.sa_family != AF_INET) continue;
if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0;
if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) continue;
memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
ifrcopy = *ifr;
ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
if ((ifrcopy.ifr_flags & IFF_UP) == 0) continue;
NSString *ip = [NSString stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);
NSString *deviceIP = @"";
for (int i=0; i < ips.count; i++) {
if (ips.count > 0) {
deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
}
}
return deviceIP;
}
/** getUUID
*
* 获取设备惟一标示符
*
*/
- (NSString *)getUUID
{
NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSLog(@"唯一识别码uuid-->%@", uuid);
return uuid;
}
/** getDeviceInfo
*
* 获取设备信息
*
*/
+ (NSString *)getDeviceInfo
{
NSString *deviceName = [SystemRelated getDeviceName];
NSString *iPhoneName = [UIDevice currentDevice].name;
NSString *appVerion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *appSign = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleSignature"];
NSString *appBundleId = [[NSBundle mainBundle] bundleIdentifier];
NSString *appName = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleDisplayName"];
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
double batteryLevel = (float)[myDevice batteryLevel];
NSString *localizedModel = [UIDevice currentDevice].localizedModel;
NSString *systemName = [UIDevice currentDevice].systemName;
NSString *systemVersion = [UIDevice currentDevice].systemVersion;
NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
struct utsname systemInfo;
uname(&systemInfo);
NSString *device_model = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
NSString *macAddress = [SystemRelated getMacAddress];
NSString *deviceIP = [SystemRelated getIPAddress:YES];
return [NSString stringWithFormat:@"\n设备型号:%@\niPhone名称:%@\nAPPBundleId:%@\nAPPName:%@\nAPP版本号:%@\nAPP签名信息:%@\n系统名称:%@\n系统版本号:%@\n唯一识别码UUID:%@\n电池电量:%0.0f\nlocalizedModel:%@\ndevice_model:%@\nMac:%@\nIPAddress:%@\n",deviceName,iPhoneName,appBundleId,appName,appVerion,appSign,systemName,systemVersion,uuid,batteryLevel * 100,localizedModel,device_model,macAddress,deviceIP];
}
/** getIPAddress
*
* 获取IP
*
*/
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [SystemRelated getIPAddresses];
NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
//筛选出IP地址格式
if([SystemRelated isValidatIP:address]) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
/** isValidatIP
*
* IP验证
*
*/
+ (BOOL)isValidatIP:(NSString *)ipAddress {
if (ipAddress.length == 0) {
return NO;
}
NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result=[ipAddress substringWithRange:resultRange];
//输出结果
NSLog(@"%@",result);
return YES;
}
}
return NO;
}
/** getIPAddresses
*
* 获取IP相关信息
*
*/
+ (NSDictionary *)getIPAddresses
{
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;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
/** getIPAddressWithWAN
*
* 获取外网IP
*
*/
+ (NSString *)getIPAddressWithWAN{
/*
http://ipof.in/json
http://ipof.in/xml
http://ipof.in/txt
If you want HTTPS you can use the same URLs with https prefix. The advantage being that even if you are on a Wifi you will get the public address.
*/
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ipof.in/txt"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
return ip;
}
@end