在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Swift获取本机IP地址,子网掩码,广播地址. 1 static func getIPAddresses() -> [String] { 2 var addresses = [String]() 3 4 // Get list of all interfaces on the local machine: 5 var ifaddr : UnsafeMutablePointer<ifaddrs> = nil 6 if getifaddrs(&ifaddr) == 0 { 7 8 // For each interface ... 9 for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) { 10 let flags = Int32(ptr.memory.ifa_flags) 11 var addr = ptr.memory.ifa_addr.memory 12 13 // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. 14 if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { 15 if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) { 16 17 // Convert interface address to a human readable string: 18 var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) 19 if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) { 20 if let address = String.fromCString(hostname) { 21 addresses.append(address) 22 } 23 } 24 } 25 } 26 } 27 freeifaddrs(ifaddr) 28 } 29 return addresses 30 } Reference:How to get Ip address in swift |
请发表评论