废话少说,直至贴上我的代码(已经带有单位转换,创建实例类后直接调用getInternetface)
//
// DetectionFlowHelper.m
// gooddriver
//
// Created by comit on 17/3/13.
// Copyright © 2017年 Comit. All rights reserved.
//
#import "DetectionFlowHelper.h"
#include <ifaddrs.h>
#include <sys/socket.h>
#include <net/if.h>
static DetectionFlowHelper* mDetectionFlow;
@implementation DetectionFlowHelper
/**
* 获取全局唯一实例
*
* @return
*/
+(id) shareInstance{
if (!mDetectionFlow) {
mDetectionFlow = [[DetectionFlowHelper alloc]init];
}
return mDetectionFlow;
}
#pragma mark - 流量监控
- (long long)getInternetface {
long long hehe = [mDetectionFlow getInterfaceBytes];
NSLog(@"速率: %@",[self bytesToAvaiUnit:hehe]);
return hehe;
}
/*获取网络流量信息*/
- (long long) getInterfaceBytes
{
struct ifaddrs *ifa_list = 0, *ifa;
if (getifaddrs(&ifa_list) == -1)
{
return 0;
}
uint32_t iBytes = 0;
uint32_t oBytes = 0;
for (ifa = ifa_list; ifa; ifa = ifa->ifa_next)
{
if (AF_LINK != ifa->ifa_addr->sa_family)
continue;
if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))
continue;
if (ifa->ifa_data == 0)
continue;
/* Not a loopback device. */
if (strncmp(ifa->ifa_name, "lo", 2))
{
struct if_data *if_data = (struct if_data *)ifa->ifa_data;
iBytes += if_data->ifi_ibytes;
oBytes += if_data->ifi_obytes;
}
}
freeifaddrs(ifa_list);
NSLog(@"\n[getInterfaceBytes-Total]%d,%d",iBytes,oBytes);
return iBytes + oBytes;
}
- (NSString *)bytesToAvaiUnit:(long long) bytes
{
if(bytes < 1024) // B
{
return [NSString stringWithFormat:@"%lldB", bytes];
}
else if(bytes >= 1024 && bytes < 1024 * 1024) // KB
{
return [NSString stringWithFormat:@"%.1fKB", (double)bytes / 1024];
}
else if(bytes >= 1024 * 1024 && bytes < 1024 * 1024 * 1024) // MB
{
return [NSString stringWithFormat:@"%.2fMB", (double)bytes / (1024 * 1024)];
}
else // GB
{
return [NSString stringWithFormat:@"%.3fGB", (double)bytes / (1024 * 1024 * 1024)];
}
}
@end