如何在xcode中检测vpn连接?

时间:2015-07-31 03:23:34

标签: ios xcode vpn

我开发了一款需要连接VPN的应用,以查看应用内容。我现在的问题是,每当用户忘记打开VPN时,我需要显示用户警告框,提醒用户连接到VPN以便在应用程序打开后查看内容(我想我需要在AppDelegate中实现此功能)。我怎样才能实现这种情况? 。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您尝试通过VPN连接到特定网站或IP地址,对吧?您可以使用Reachability来检测IP地址是否可访问,以及Apple sample code can be found here

可以在these related questions中看到更多信息。

答案 1 :(得分:1)

我写了一个小助手来检测您要寻找的东西。这是代码段:

struct VpnChecker {

    private static let vpnProtocolsKeysIdentifiers = [
        "tap", "tun", "ppp", "ipsec", "utun"
    ]

    static func isVpnActive() -> Bool {
        guard let cfDict = CFNetworkCopySystemProxySettings() else { return false }
        let nsDict = cfDict.takeRetainedValue() as NSDictionary
        guard let keys = nsDict["__SCOPED__"] as? NSDictionary,
            let allKeys = keys.allKeys as? [String] else { return false }

        // Checking for tunneling protocols in the keys
        for key in allKeys {
            for protocolId in vpnProtocolsKeysIdentifiers
                where key.starts(with: protocolId) {
                // I use start(with:), so I can cover also `ipsec4`, `ppp0`, `utun0` etc...
                return true
            }
        }
        return false
    }
}

用法:VpnChecker.isVpnActive()

我还写了一篇有关here

的博客文章

答案 2 :(得分:0)

要检查连接是否通过VPN,请实施此代码,并在每次用户使用该应用程序时调用它,因此必须在func applicationDidBecomeActive(_ application: UIApplication) { }func applicationWillEnterForeground(_ application: UIApplication) { }中进行处理

func isVPNConnected() -> Bool {
    let cfDict = CFNetworkCopySystemProxySettings()
    let nsDict = cfDict!.takeRetainedValue() as NSDictionary
    let keys = nsDict["__SCOPED__"] as! NSDictionary

    for key: String in keys.allKeys as! [String] {
        if (key == "tap" || key == "tun" || key == "ppp" || key == "ipsec" || key == "ipsec0") {
            return true
        }
    }
    return false
}