乐闻世界logo
搜索文章和话题

How to get Ip address in swift

1个答案

1

In Swift, obtaining the device's IP address can be implemented using specific network interface functions. Specifically, the getifaddrs() function is used to iterate over all network interfaces of the device and identify the associated IP addresses. Below is a Swift-based example code demonstrating how to retrieve the current device's IP address:

swift
import Foundation import SystemConfiguration func getIPAddress() -> String? { var address: String? var ifaddr: UnsafeMutablePointer<ifaddrs>? if getifaddrs(&ifaddr) == 0 { var ptr = ifaddr while ptr != nil { let flags = Int32((ptr?.pointee.ifa_flags)!) var addr = ptr?.pointee.ifa_addr.pointee if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { if addr?.sa_family == UInt8(AF_INET) || addr?.sa_family == UInt8(AF_INET6) { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(ptr?.pointee.ifa_addr, socklen_t((addr?.sa_len)!), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { if let addressString = String(validatingUTF8: hostname) { if addr?.sa_family == UInt8(AF_INET) { // Only retrieve IPv4 addresses address = addressString break } } } } } ptr = ptr?.pointee.ifa_next } freeifaddrs(ifaddr) } return address }

The function first defines a mutable pointer ifaddr to store the network interface address structure. By calling getifaddrs(&ifaddr), we populate this linked list of network interface structures containing all network interface information.

The function then iterates through this list, examining each network interface. By checking the interface flags, we focus only on those that are active and running, while ignoring loopback addresses. By evaluating the sa_family attribute, we distinguish between IPv4 and IPv6 addresses. In this example, we only consider IPv4 addresses.

Using getnameinfo(), we convert the network address into a character array, representing the IP address in string form. Finally, if a valid IPv4 address is found, it is stored in the address variable and returned.

Please note that since obtaining the IP address involves low-level network configuration, this code is best run on a real device rather than a simulator. Additionally, considering that network configurations may change, the IP address obtained through this method may vary with network environment changes.

2024年8月5日 10:06 回复

你的答案