0

我正在 swift 5 中开发一个 VPN 应用程序。我们正在使用 NEVPNManager 来处理所有 VPN 配置。我们想要的功能之一是在用户连接到我们的 VPN 时测量用户的使用数据。我们应该怎么做 ?

4

1 回答 1

2

NEVPNManager 不提供任何满足您要求的方法。以下是个人在应用程序中使用的解决方案。

解决方案:搜索合适的网络接口并开始读取 In 和 Out 字节。
en0 指 Wifi pdp_ip 指 Cellular 网络

+ (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]};}
于 2020-06-04T11:24:16.623 回答