iOS 网络流量统计
计算项目中流量的发送、接受和消耗
- (NSDictionary*)getTrafficMonitorings
{
NSDictionary * trafficDict = [[NSDictionary alloc] init];
BOOLsuccess;
structifaddrs*addrs;
conststructifaddrs*cursor;
conststructif_data*networkStatisc;
intWiFiSent =0;
intWiFiReceived =0;
intWWANSent =0;
intWWANReceived =0;
NSString *name=[[NSString alloc]init];
success =getifaddrs(&addrs) ==0;
if(success) {
cursor = addrs;
while(cursor !=NULL) {
name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
if(cursor->ifa_addr->sa_family==AF_LINK) {
//wifi消耗流量
if([namehasPrefix:@"en"]) {
networkStatisc = (conststructif_data*) cursor->ifa_data;
WiFiSent+=networkStatisc->ifi_obytes;
WiFiReceived+=networkStatisc->ifi_ibytes;
}
//移动网络消耗流量
if([namehasPrefix:@"pdp_ip0"]) {
networkStatisc = (conststructif_data*) cursor->ifa_data;
WWANSent+=networkStatisc->ifi_obytes;
WWANReceived+=networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
NSString*WiFiSentTraffic = [NSStringstringWithFormat:@"%d",WiFiSent];
NSString*WiFiReceivedTraffic = [NSStringstringWithFormat:@"%d",WiFiReceived];
NSString*WiFiTotalTraffic = [NSStringstringWithFormat:@"%d",WiFiSent + WiFiReceived];
NSString*WWANSentTraffic = [NSStringstringWithFormat:@"%d",WWANSent];
NSString*WWANReceivedTraffic = [NSStringstringWithFormat:@"%d",WWANReceived];
NSString*WWANTotalTraffic = [NSStringstringWithFormat:@"%d",WWANSent+WWANReceived];
trafficDict =@{
@"WiFiSentTraffic":WiFiSentTraffic,
@"WiFiReceivedTraffic":WiFiReceivedTraffic,
@"WiFiTotalTraffic":WiFiTotalTraffic,
@"WWANSentTraffic":WWANSentTraffic,
@"WWANReceivedTraffic":WWANReceivedTraffic,
@"WWANTotalTraffic":WWANTotalTraffic
};
/*
WiFi状态下发送流量
WiFi状态下接收流量
WiFi状态下消耗总流量
移动网络下发送流量
移动网络下接收流量
移动网络下消耗总流量
*/
returntrafficDict;
}