import Foundation /// Local IPv4 address discovery — which networks is this Mac actually on? /// Used by the install join gate (mesh membership evidence) and the phone-setup QR /// (advertising this Mac's bridge endpoints to a scanning phone). public enum LocalNetwork { /// Every IPv4 address bound to a local interface, loopback excluded. public static func ipv4Addresses() -> [String] { var addrs: UnsafeMutablePointer? guard getifaddrs(&addrs) == 0 else { return [] } defer { freeifaddrs(addrs) } var out: [String] = [] var cursor = addrs while let ifa = cursor?.pointee { defer { cursor = ifa.ifa_next } guard let sa = ifa.ifa_addr, sa.pointee.sa_family == sa_family_t(AF_INET) else { continue } var addr = sockaddr_in() memcpy(&addr, sa, MemoryLayout.size) var ip = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN)) var sin = addr.sin_addr inet_ntop(AF_INET, &sin, &ip, socklen_t(INET_ADDRSTRLEN)) let s = String(cString: ip) if s != "127.0.0.1" { out.append(s) } } return out } /// This Mac's mesh (10.9.0.x) address, when the tunnel is configured. public static func meshAddress() -> String? { ipv4Addresses().first { $0.hasPrefix("10.9.0.") } } /// This Mac's best non-mesh private address (the LAN leg), if any. public static func lanAddress() -> String? { let v4 = ipv4Addresses().filter { !$0.hasPrefix("10.9.0.") } // Prefer the home LAN subnet, then any RFC1918 address. return v4.first { $0.hasPrefix("10.0.0.") } ?? v4.first { $0.hasPrefix("192.168.") || $0.hasPrefix("10.") || $0.hasPrefix("172.") } } }