1. 程式人生 > >iOS中如何獲取當前網路及其本地IP(Swift)

iOS中如何獲取當前網路及其本地IP(Swift)

···

//獲取當前網路

func getUsedSSID() -> String {let interfaces = CNCopySupportedInterfaces()

var ssid = ""

if interfaces != nil {

let interfacesArray = CFBridgingRetain(interfaces) as! Array<AnyObject>

if interfacesArray.count > 0 {

let interfaceName = interfacesArray[0] as! CFString

let ussafeInterfaceData = CNCopyCurrentNetworkInfo

(interfaceName)

if (ussafeInterfaceData != nil) {

let interfaceData = ussafeInterfaceData as! Dictionary<String, Any>

ssid = interfaceData["SSID"]! as! String

}

}

}

return ssid

}

//獲取本機ip

func getLocalIPAddressForCurrentWiFi() -> String? {

var address: String?

// get list of all interfaces on the local machine

var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil

guard getifaddrs(&ifaddr) == 0 else {

return nil

}

guard let firstAddr = ifaddr else {

return nil

}

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 == "en0" {

// Convert interface address to a human readable string

var addr = interface.ifa_addr.pointee

var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))

getnameinfo(&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

}


···