iOS Xcode Swift-如何获取热点连接设备的IP地址?

时间:2019-12-04 19:11:41

标签: ios swift iphone xcode

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

Swift 5或任何其他开源代码中是否有针对它的API?

1 个答案:

答案 0 :(得分:0)

请参考下面的代码。

要获取热点连接设备的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