0

I'm checking my users data consumption using the method below, taken from here. It's working well most of the time, but for some users it's returning a negative value. In other words the WWANReceived is negative.

How can that be? Is there a fix?

+ (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];
}
Community
  • 1
  • 1
Eddy
  • 3,533
  • 13
  • 59
  • 89

1 Answers1

3

Maybe you've already solved this I was just testing the same example and came upon this.

You have to change the type from int to long long to handle bigger values. What you're seeing is integer overflow that happens after 2GB of traffic.

jab11
  • 867
  • 1
  • 8
  • 15
  • Resurrecting this from the bowels of stack overflow... Which variables did you have to change from int to long long, and did it work? You should accept the answer if so! – Amos Apr 29 '15 at 03:21
  • @Amos all four int variables in there should be of long long type. also the returning NSNumbers whould be created with numberWithLongLong: calls. – jab11 Apr 30 '15 at 10:18