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 ?
Asked
Active
Viewed 350 times
1 Answers
2
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]};}

munibsiddiqui
- 435
- 5
- 15
-
1Great solution. But there is a problem. `ifi_obytes` or `ifi_ibytes` are total number of octets sent and received respectively since the last reboot. This can't help to measure only since the VPN has been activated. – Houman Mar 19 '22 at 17:37