Skip to content

Instantly share code, notes, and snippets.

@cute
Forked from azwan082/is_connected_to_vpn.swift
Created December 30, 2023 11:16
Show Gist options
  • Save cute/aa05b6c9b0522467e95fc5d7d4d36098 to your computer and use it in GitHub Desktop.
Save cute/aa05b6c9b0522467e95fc5d7d4d36098 to your computer and use it in GitHub Desktop.
Check if iOS app is connected to VPN
func isConnectedToVpn() -> Bool {
let host = "www.example.com"
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else {
return false
}
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) == false {
return false
}
let isOnline = flags.contains(.reachable) && !flags.contains(.connectionRequired)
if !isOnline {
return false
}
let isMobileNetwork = flags.contains(.isWWAN)
let isTransientConnection = flags.contains(.transientConnection)
if isMobileNetwork {
if let settings = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? Dictionary<String, Any>,
let scopes = settings["__SCOPED__"] as? [String:Any] {
for (key, _) in scopes {
if key.contains("tap") || key.contains("tun") || key.contains("ppp") {
return true
}
}
}
return false
} else {
return isTransientConnection
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment