gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:25:00 45 4
gpt4 key购买 nike

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

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

最佳答案

请引用下面的代码。

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

关于iOS Xcode Swift - 如何获取热点连接设备的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183160/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com