首先需要開啟一個(gè)定時(shí)器,每隔1S獲取一次當(dāng)前網(wǎng)速
#pragma mark - 計(jì)時(shí)器
- (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;
}
然后開始獲取網(wǎng)速:
引入頭文件:
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
相關(guān)代碼:
#pragma mark 當(dāng)前網(wǎng)速
- (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 轉(zhuǎn)換
- (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判斷,類似的參數(shù)還有很多,比如lo、en0、pdp_ip0,具體代表什么意思可以參考mac ifconfig解釋
可以知道lo0是loopback的意思,具體意思查看loopback,用途可以參考loopback(本地回環(huán))接口的作用,在里面第12條:
12、NetFlow Flow-Export
從一個(gè)路由器向NetFlow采集器傳送流量數(shù)據(jù),以實(shí)現(xiàn)流量分析和計(jì)費(fèi)目的,將路由器的Router的Loopback地址作為路由器所有輸出流量統(tǒng)計(jì)數(shù)據(jù)包的源地址,可以在服務(wù)器或者是服務(wù)器外圍提供更精確,成本更低的過(guò)濾配置。