41 lines
1.5 KiB
Swift
41 lines
1.5 KiB
Swift
import Foundation
|
|
import Darwin
|
|
|
|
/// The address observed by an external HTTPS service, not a per-interface address.
|
|
actor PublicIPAddressService {
|
|
static let shared = PublicIPAddressService()
|
|
private let session: URLSession
|
|
|
|
init(session: URLSession = .shared) { self.session = session }
|
|
|
|
private var cached: (route: String, date: Date, address: String?)?
|
|
|
|
func address(route: String) async -> String? {
|
|
if let cached, cached.route == route, Date().timeIntervalSince(cached.date) < 600 {
|
|
return cached.address
|
|
}
|
|
var request = URLRequest(url: URL(string: "https://api.ipify.org")!)
|
|
request.timeoutInterval = 5
|
|
request.cachePolicy = .reloadIgnoringLocalCacheData
|
|
let address: String?
|
|
do {
|
|
let (data, response) = try await session.data(for: request)
|
|
let value = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
|
var ipv4 = in_addr()
|
|
var ipv6 = in6_addr()
|
|
guard (response as? HTTPURLResponse)?.statusCode == 200,
|
|
value.utf8.count <= 45,
|
|
inet_pton(AF_INET, value, &ipv4) == 1 || inet_pton(AF_INET6, value, &ipv6) == 1 else {
|
|
cached = (route, Date(), nil)
|
|
return nil
|
|
}
|
|
address = value
|
|
} catch {
|
|
if Task.isCancelled { return nil }
|
|
address = nil
|
|
}
|
|
cached = (route, Date(), address)
|
|
return address
|
|
}
|
|
}
|