首先需要开启一个定时器,每隔1S
获取一次当前网速
#pragma mark - 计时器
- (NSTimer *)timer{
if(!_timer){
_timer =[NSTimer timerWithTimeInterval:1 target:self selector:@selector(currentNetSpeed) userInfo:nil repeats:YES];
[_timer setFireDate:[NSDate distantFuture]];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}
return _timer;
}
#pragma mark 暂停
- (void)distantFutureTimer{
[self.timer setFireDate:[NSDate distantFuture]];
}
#pragma mark 开始
- (void)startTimer{
[self.timer setFireDate:[NSDate distantPast]];
}
#pragma mark 停止
- (void)stopTimer{
[self.timer invalidate];
self.timer = nil;
}
然后开始获取网速:
引入头文件:
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
相关代码:
#pragma mark 当前网速
- (void)currentNetSpeed {
struct ifaddrs *ifa_list = 0, *ifa;
if (getifaddrs(&ifa_list) == -1) return;
uint32_t iBytes = 0;
uint32_t oBytes = 0;
uint32_t allFlow = 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;
// network
if (strncmp(ifa->ifa_name, "lo0", 2)) {
struct if_data* if_data = (struct if_data*)ifa->ifa_data;
iBytes += if_data->ifi_ibytes;
oBytes += if_data->ifi_obytes;
allFlow = iBytes + oBytes;
}
}
freeifaddrs(ifa_list);
if (_iBytes != 0) {
_downloadNetSpeed = [[self stringWithbytes:iBytes - _iBytes] stringByAppendingString:@"/s"];
}
_iBytes = iBytes;
if (_oBytes != 0) {
_uploadNetSpeed = [[self stringWithbytes:oBytes - _oBytes] stringByAppendingString:@"/s"];
}
_oBytes = oBytes;
}
#pragma mark 转换
- (NSString *)stringWithbytes:(int)bytes {
if (bytes < 1024) { // B
return [NSString stringWithFormat:@"%dB", bytes];
} else if (bytes >= 1024 && bytes < 1024 * 1024) { // KB
return [NSString stringWithFormat:@"%.0fKB", (double)bytes / 1024];
} else if (bytes >= 1024 * 1024 && bytes < 1024 * 1024 * 1024) { // MB
return [NSString stringWithFormat:@"%.1fMB", (double)bytes / (1024 * 1024)];
} else { // GB
return [NSString stringWithFormat:@"%.1fGB", (double)bytes / (1024 * 1024 * 1024)];
}
}
这里我选择使用lo0
判断,类似的参数还有很多,比如lo
、en0
、pdp_ip0
,具体代表什么意思可以参考mac ifconfig解释
可以知道lo0
是loopback
的意思,具体意思查看loopback,用途可以参考loopback(本地回环)接口的作用,在里面第12条:
12、NetFlow Flow-Export
从一个路由器向NetFlow采集器传送流量数据,以实现流量分析和计费目的,将路由器的Router的Loopback地址作为路由器所有输出流量统计数据包的源地址,可以在服务器或者是服务器外围提供更精确,成本更低的过滤配置。
作者:宥落
链接:https://www.jianshu.com/p/f50fec0076ec
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
网友评论