wifi 3G 流量
//
// flowStatis.c
// Test
//
// Created by iXcoder on 12-7-19.
// Copyright (c) 2012年 iXcoder. All rights reserved.
//
#import <Foundation/Foundation.h>
#include <stdio.h>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <net/if.h>
//3G流量统计
int getGprs3GFlowIOBytes() {
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;
if (!strcmp(ifa->ifa_name,"pdp_ip0")) {
struct if_data *if_data = (struct if_data*)ifa->ifa_data;
iBytes += if_data->ifi_ibytes;
oBytes += if_data->ifi_obytes;
NSLog(@"%s :iBytes is %d, oBytes is %d",ifa->ifa_name, iBytes, oBytes);
}
}
freeifaddrs(ifa_list);
return iBytes + oBytes;
}
//Wifi流量统计
- (long long int)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;
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;
NSLog(@"%s :iBytes is %d, oBytes is %d", ifa->ifa_name, iBytes, oBytes);
}
}
freeifaddrs(ifa_list);
return iBytes+oBytes;
}
将流量值写入文件,或SQLite,或使用CoreData,方便按天、周、月统计。