我正在使用下面的方法检查我的用户的数据消耗,该方法取自here。它在大多数情况下工作得很好,但对于一些用户来说,它会返回一个负值。换句话说,WWANReceived是负的。
这怎么可能呢?有什么解决办法吗?
+ (NSArray *)getDataCounters {
BOOL success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct if_data *networkStatisc;
int WiFiSent = 0;
int WiFiReceived = 0;
int WWANSent = 0;
int WWANReceived = 0;
NSString *name = [[NSString alloc]init];
// getifmaddrs
success = getifaddrs(&addrs) == 0;
if (success)
{
cursor = addrs;
while (cursor != NULL)
{
name = [NSString stringWithFormat:@"%s",cursor->ifa_name];
// names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
if (cursor->ifa_addr->sa_family == AF_LINK)
{
if ([name hasPrefix:@"en"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WiFiSent += networkStatisc->ifi_obytes;
WiFiReceived += networkStatisc->ifi_ibytes;
}
if ([name hasPrefix:@"pdp_ip"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WWANSent += networkStatisc->ifi_obytes;
WWANReceived += networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil];
}发布于 2014-11-17 03:01:13
也许你已经解决了这个问题,我只是在测试相同的例子,然后发现了这个。
为了处理更大的值,您必须将类型从int更改为long long。您所看到的是在2 2GB流量之后发生的整数溢出。
https://stackoverflow.com/questions/26037378
复制相似问题