Skip to content

Instantly share code, notes, and snippets.

@popmedic
Last active June 30, 2021 20:02
Show Gist options
  • Save popmedic/cbdfa9da7287d4dd085d758301a1e64f to your computer and use it in GitHub Desktop.
Save popmedic/cbdfa9da7287d4dd085d758301a1e64f to your computer and use it in GitHub Desktop.
A quick example of how to get the External IP address of a device that is on a LAN connected by an Access Point to the WAN.
import SwiftUI
import Network
class ExternIP: ObservableObject {
@Published var address: String = "unknown"
@Published var isV6Supported: Bool = false
init() {
queue = DispatchQueue(label: "monitor")
monitor = NWPathMonitor()
monitor.pathUpdateHandler = { [weak self] path in
guard let self = self else { return }
self.getIP { (address) in
DispatchQueue.main.async {
self.isV6Supported = path.supportsIPv6
self.address = address
}
}
}
monitor.start(queue: queue)
}
private let queue: DispatchQueue
private let monitor: NWPathMonitor
private func getIP(complete: @escaping (String) -> Void) {
let request = URLRequest(url: URL(string: "https://icanhazip.com/")!)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let string: String
if let error = error { string = error.localizedDescription }
else if let data = data { string = String(data: data, encoding: .utf8) ?? "bad data" }
else { string = "no data" }
complete(string)
}
task.resume()
}
}
struct ExternIPView: View {
@ObservedObject var ip = ExternIP()
let connect = Connection()
var body: some View {
VStack {
Text(ip.address)
.padding()
Text("Supports v6?: \(ip.isV6Supported.description)")
.padding()
}
}
}
@main
struct ListenerConnectionIPv6App: App {
var body: some Scene {
WindowGroup {
ExternIPView()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment