aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuard/WireGuard/Tunnel/InternetReachability.swift
diff options
context:
space:
mode:
Diffstat (limited to 'WireGuard/WireGuard/Tunnel/InternetReachability.swift')
-rw-r--r--WireGuard/WireGuard/Tunnel/InternetReachability.swift51
1 files changed, 51 insertions, 0 deletions
diff --git a/WireGuard/WireGuard/Tunnel/InternetReachability.swift b/WireGuard/WireGuard/Tunnel/InternetReachability.swift
new file mode 100644
index 0000000..2e50852
--- /dev/null
+++ b/WireGuard/WireGuard/Tunnel/InternetReachability.swift
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: MIT
+// Copyright © 2018 WireGuard LLC. All Rights Reserved.
+
+import SystemConfiguration
+
+class InternetReachability {
+
+ enum Status {
+ case unknown
+ case notReachable
+ case reachableOverWiFi
+ case reachableOverCellular
+ }
+
+ static func currentStatus() -> Status {
+ var status: Status = .unknown
+ if let reachabilityRef = InternetReachability.reachabilityRef() {
+ var flags = SCNetworkReachabilityFlags(rawValue: 0)
+ SCNetworkReachabilityGetFlags(reachabilityRef, &flags)
+ status = Status(reachabilityFlags: flags)
+ }
+ return status
+ }
+
+ private static func reachabilityRef() -> SCNetworkReachability? {
+ let addrIn = sockaddr_in(sin_len: UInt8(MemoryLayout<sockaddr_in>.size),
+ sin_family: sa_family_t(AF_INET),
+ sin_port: 0,
+ sin_addr: in_addr(s_addr: 0),
+ sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
+ return withUnsafePointer(to: addrIn) { addrInPtr in
+ addrInPtr.withMemoryRebound(to: sockaddr.self, capacity: 1) { addrPtr in
+ return SCNetworkReachabilityCreateWithAddress(nil, addrPtr)
+ }
+ }
+ }
+}
+
+extension InternetReachability.Status {
+ init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
+ var status: InternetReachability.Status = .notReachable
+ if flags.contains(.reachable) {
+ if flags.contains(.isWWAN) {
+ status = .reachableOverCellular
+ } else {
+ status = .reachableOverWiFi
+ }
+ }
+ self = status
+ }
+}