Swift获取WIFI的SSID 和Swift获取IP

emacs

WIFI的SSID

先导入 import SystemConfiguration.CaptiveNetwork

1
2
3
4
5
6
7
8
9
10
11
12
13
func getSSID() -> String? {
let interfaces: CFArray! = CNCopySupportedInterfaces()?.takeRetainedValue()
if interfaces == nil { return nil }

let if0: UnsafePointer<Void>? = CFArrayGetValueAtIndex(interfaces, 0)
if if0 == nil { return nil }

let interfaceName: CFStringRef = unsafeBitCast(if0!, CFStringRef.self)
let dictionary = CNCopyCurrentNetworkInfo(interfaceName)?.takeRetainedValue() as NSDictionary?
if dictionary == nil { return nil }

return dictionary?[kCNNetworkInfoKeySSID as String] as? String
}

Swift获取IP

先在桥接文件中加入 #include <ifaddrs.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Return IP address of WiFi interface (en0) as a String, or `nil`
func getWiFiAddress() -> String? {
var address : String?

// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {

// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
let interface = ptr.memory

// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.memory.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

// Check interface name:
if let name = String.fromCString(interface.ifa_name) where name == "en0" {

// Convert interface address to a human readable string:
var addr = interface.ifa_addr.memory
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
getnameinfo(&addr, socklen_t(interface.ifa_addr.memory.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String.fromCString(hostname)
}
}
}
freeifaddrs(ifaddr)
}

return address
}