【问题标题】:iOS Xcode Swift - How to get hotspot connected devices IP address?iOS Xcode Swift - 如何获取热点连接设备的 IP 地址?
【发布时间】:2020-03-29 16:15:24
【问题描述】:

我需要使用 Swift 5 开发一个 iOS 应用程序来查找我的 iPhone 热点连接设备的 IP 信息。

在 Swift 5 或任何其他开源代码中是否有任何 API?

【问题讨论】:

    标签: ios swift iphone xcode


    【解决方案1】:

    请参考以下代码。

    要获取热点连接设备的 IP,请使用 Network.wifi 。

    enum Network: String {
        case wifi = "en0"
        case cellular = "pdp_ip0"
        case ipv4 = "ipv4"
        case ipv6 = "ipv6"
    }
    
    func getAddress(for network: Network) -> String? {
        var address: String?
    
        // Get list of all interfaces on the local machine:
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&ifaddr) == 0 else { return nil }
        guard let firstAddr = ifaddr else { return nil }
    
        // For each interface ...
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let interface = ifptr.pointee
    
            // Check for IPv4 or IPv6 interface:
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
    
                // Check interface name:
                let name = String(cString: interface.ifa_name)
                if name == network.rawValue {
    
                    // Convert interface address to a human readable string:
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_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
    }
    
    print("wifi: \(String(describing: getAddress(for: .wifi)))")
    

    更多信息请参考以下链接:

    Swift - Get device's WIFI IP Address

    Get IPAddress of iPhone or iPad device Using Swift 3

    【讨论】:

    • 感谢您的信息。这为应用程序提供了运行设备的 IP 地址。但我想获取热点连接的设备 IP 地址。例如,我在我的 iPhone 中启用了个人热点,并通过该热点连接了我的 iPad。现在通过我的 iPhone,我想使用我的应用程序获取 iPad 的 IP 地址。
    • @Joe 你能告诉我你是如何使用你的应用程序获得 iPad 的 IP 地址的吗?我也需要做同样的事情。你能帮帮我吗?
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多