Sunday, March 22, 2015

iOS checking WiFi Data usage

The data usage of a WiFi Device can be calculated like below. 

Below code snippet can help to get the data counters. 

BOOL   success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;
    
    int WiFiSent = 0;
    int WiFiReceived = 0;
    
    int WiFiPacketsSent = 0;
    int WiFiPacketsReceived = 0;
    
    int WWANSent = 0;
    int WWANReceived = 0;
    
    NSString *name=[[NSString alloc]init];
    
    success = getifaddrs(&addrs) == 0;
    if (success)
    {
        cursor = addrs;
        while (cursor != NULL)
        {
            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
            NSLog(@"ifa_name %s == %@\n", cursor->ifa_name,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;
                    
                    WiFiPacketsSent+= networkStatisc->ifi_opackets;
                    WiFiPacketsReceived+= networkStatisc->ifi_ipackets;
                    



The complete code can be found here 

https://drive.google.com/file/d/0B0ZgwdHsnw1bTDhOVFNBekJIaDg/view?usp=sharing 

References:



No comments:

Post a Comment