今天偶然看到了这位兄台的文章https://www.jianshu.com/p/8005d7e05944判断是否是vpn,哈哈这哥们还真是脑洞大开。
其实在这位老兄https://github.com/dustturtle/RealReachability的项目包含了检测VPN的方法
通过判断tap tun ipsec ppp 这些字段是否在CFNetworkCopySystemProxySettings里来判断vpn是否开启
局部代码
NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
NSArray *keys = [dict[@"__SCOPED__"] allKeys];
for (NSString *key in keys) {
if ([key rangeOfString:@"tap"].location != NSNotFound ||
[key rangeOfString:@"tun"].location != NSNotFound ||
[key rangeOfString:@"ipsec"].location != NSNotFound ||
[key rangeOfString:@"ppp"].location != NSNotFound){
flag = YES;
break;
}
}
整个方法
- (BOOL)isVPNOn
{
BOOL flag = NO;
NSString *version = [UIDevice currentDevice].systemVersion;
// need two ways to judge this.
if (version.doubleValue >= 9.0)
{
NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
NSArray *keys = [dict[@"__SCOPED__"] allKeys];
for (NSString *key in keys) {
if ([key rangeOfString:@"tap"].location != NSNotFound ||
[key rangeOfString:@"tun"].location != NSNotFound ||
[key rangeOfString:@"ipsec"].location != NSNotFound ||
[key rangeOfString:@"ppp"].location != NSNotFound){
flag = YES;
break;
}
}
}
else
{
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
temp_addr = interfaces;
while (temp_addr != NULL)
{
NSString *string = [NSString stringWithFormat:@"%s" , temp_addr->ifa_name];
if ([string rangeOfString:@"tap"].location != NSNotFound ||
[string rangeOfString:@"tun"].location != NSNotFound ||
[string rangeOfString:@"ipsec"].location != NSNotFound ||
[string rangeOfString:@"ppp"].location != NSNotFound)
{
flag = YES;
break;
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
}
return flag;
}
这个是判断系统的vpn状态,还有一种是调起vpnExtension或着说NEVPNManager的时候的vpn状态可以通过实例化NEVPNManager,然后通过manager.connection.status来获取当前的vpn状态