NEVPNManager - How to track data usage of VPN in swift

432 Views Asked by At

I am working on a VPN app in swift 5. We are using NEVPNManager to handle all VPN configs. One of the features we would like is to measure the user's usage data while they are connected to our VPN. How can we do this ?

1

There are 1 best solutions below

1
munibsiddiqui On

NEVPNManager doesn't offer any method that fulfil your requirement. Following is the solution is personally use in application.

Solution: Search for the suitable Network Interface and start reading the In and Out bytes.
en0 refers to Wifi pdp_ip refers to Cellular network

+ (NSDictionary *) DataCounters{

struct ifaddrs *addrs;
const struct ifaddrs *cursor;

u_int32_t WiFiSent = 0;
u_int32_t WiFiReceived = 0;
u_int32_t WWANSent = 0;
u_int32_t WWANReceived = 0;

if (getifaddrs(&addrs) == 0)
{
    cursor = addrs;
    while (cursor != NULL)
    {
        if (cursor->ifa_addr->sa_family == AF_LINK)
        {


            // name of interfaces:
            // en0 is WiFi
            // pdp_ip0 is WWAN
            NSString *name = [NSString stringWithFormat:@"%s",cursor->ifa_name];
            if ([name hasPrefix:@"en"])
            {
                const struct if_data *ifa_data = (struct if_data *)cursor->ifa_data;
                if(ifa_data != NULL)
                {
                    WiFiSent += ifa_data->ifi_obytes;
                    WiFiReceived += ifa_data->ifi_ibytes;
                }
            }

            if ([name hasPrefix:@"pdp_ip"])
            {
                const struct if_data *ifa_data = (struct if_data *)cursor->ifa_data;
                if(ifa_data != NULL)
                {
                    WWANSent += ifa_data->ifi_obytes;
                    WWANReceived += ifa_data->ifi_ibytes;
                }
            }
        }

        cursor = cursor->ifa_next;
    }

    freeifaddrs(addrs);
}

return @{DataCounterKeyWiFiSent:[NSNumber numberWithUnsignedInt:WiFiSent],
         DataCounterKeyWiFiReceived:[NSNumber numberWithUnsignedInt:WiFiReceived],
         DataCounterKeyWWANSent:[NSNumber numberWithUnsignedInt:WWANSent],
         DataCounterKeyWWANReceived:[NSNumber numberWithUnsignedInt:WWANReceived]};}