title: iPhone Data Usage Tracking/Monitoring
body: <p>I've searched over this topic but found very few details which were helpful. With these details I've tried to cook some code as follows.</p>
  
  <p><strong>Note: Please compare the details shared in this post with other posts before marking this as DUPLICATE, and not just by the subject.</strong></p>
  
  <pre><code>- (NSArray *)getDataCountersForType:(int)type {
      BOOL success;
      struct ifaddrs *addrs = nil;
      const struct ifaddrs *cursor = nil;
      const struct sockaddr_dl *dlAddr = nil;
      const struct if_data *networkStatisc = nil; 
  
      int dataSent = 0;
      int dataReceived = 0;
  
      success = getifaddrs(&amp;addrs) == 0;
      if (success) {
          cursor = addrs;
          while (cursor != NULL) {
              if (cursor-&gt;ifa_addr-&gt;sa_family == AF_LINK) {
                  dlAddr = (const struct sockaddr_dl *) cursor-&gt;ifa_addr;
                  networkStatisc = (const struct if_data *) cursor-&gt;ifa_data;
  
                  if (type == WiFi) {
                      dataSent += networkStatisc-&gt;ifi_opackets;
                      dataReceived += networkStatisc-&gt;ifi_ipackets;   
                  }
                  else if (type == WWAN) {
                      dataSent += networkStatisc-&gt;ifi_obytes;
                      dataReceived += networkStatisc-&gt;ifi_ibytes; 
                  }
              }
              cursor = cursor-&gt;ifa_next;
          }
          freeifaddrs(addrs);
      }       
      return [NSArray arrayWithObjects:[NSNumber numberWithInt:dataSent], [NSNumber numberWithInt:dataReceived], nil];    
  }
  </code></pre>
  
  <p>This code collects information of internet usage of an iPhone device (and not my application alone). </p>
  
  <p>Now, if I use internet through WiFi or through 3G, I get the the data (bytes) only in <code>ifi_obytes</code> (sent) and <code>ifi_ibytes</code> (received) but I think I should get WiFi usage in <code>ifi_opackets</code> and <code>ifi_ipackets</code>.</p>
  
  <p>Also wanted to add that if I'm connected to a WiFi network, but am not using internet, I still get value added to <code>ifi_obytes</code> and <code>ifi_ibytes</code>.</p>
  
  <p>May be I'm wrong in the implementation or understanding. Need someone to help me out.</p>
  
  <hr>
  
  <p>Edit: Instead of <code>AF_LINK</code> I tried <code>AF_INET</code> (<code>sockaddr_in</code> instead of <code>sockaddr_dl</code>). This crashes the application.</p>