swift获取热点Gateway地址

swift获取热点Gateway地址,第1张

在网上搜了很多文章,给出的都是连接Wi-Fi后如何获取本机IP:

// 获取本机Wi-Fi IP
func getWIFIIP() -> String? {
        var address: String?
        var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
        
        guard getifaddrs(&ifaddr) == 0 else {
            return nil
        }
        
        guard let firstAddr = ifaddr else {
            return nil
        }
        
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let interface = ifptr.pointee
            
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                let name = String(cString: interface.ifa_name)
                if name == "en0" {
                    var addr = interface.ifa_addr.pointee
                    var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostName)
                }
            }
        }
        freeifaddrs(ifaddr)
        return address
    }

获取路由器IP方式如下:

class NWPathMonitor

官方解释:
An observer that you use to monitor and react to network changes.

官方文档

首先引入Network库

// 监听所有网络类型的状态
let monitor = NWPathMonitor()
// 监听特定网络类型状态,主要就是wifi和cellular
let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
// 判断当前是否正在使用某种网络
let ret = monitor.currentPath.usesInterfaceType(.wifi)
// 获取热点Gateway
    func getGatewayAddr() {
        // 监听Wi-Fi是否连接
        let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
        // 连上Wi-Fi后获取IP
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                let endpoint = String(describing: path.gateways[0])
                self.gatewayAddr = endpoint.components(separatedBy: (":"))[0]
                print("gatewayAddr: \(self.gatewayAddr)")
            }
        }
        
        // Starts monitoring path changes, and sets a queue on which to deliver path events.
        monitor.start(queue: DispatchQueue(label: "get gateway successed"))
    }

很多东西官方文档都有说明,中文互联网iOS的博客确实不好找,还是得好好学英语。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993313.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存