如何使用Swift从OS X获取MAC地址 [英] How to get MAC address from OS X with Swift
问题描述
是否可以使用Swift获取MAC地址?
Is it possible to get the MAC address using Swift?
MAC地址是Wi-Fi或机场的主要地址.
The MAC address being the primary address for the Wi-Fi or Airport.
我正在尝试制作OS X应用程序.
I'm trying to make a OS X application.
推荐答案
免责声明:不是可用于生产.它可能会被App Store拒绝.如果将来ifconfig
的输出发生更改,也会出错. 之所以这样做,是因为我缺乏翻译链接中给出的C代码的技能.它不能替代完整的Swift解决方案.话虽如此,它的工作原理...
DISCLAIMER: this is not production-ready. It would probably be rejected by the App Store. It's also subject to errors if the output of ifconfig
changes in the future. I've made this because I lacked the skills to translate the C code given in the links. It does not replace a full Swift solution. That being said, it works...
获取ifconfig
的输出并进行解析以获取与接口关联的MAC地址(在此示例中为en0
):
Get ifconfig
's output and parse it to get the MAC address associated with an interface (en0
in this example):
let theTask = NSTask()
let taskOutput = NSPipe()
theTask.launchPath = "/sbin/ifconfig"
theTask.standardOutput = taskOutput
theTask.standardError = taskOutput
theTask.arguments = ["en0"]
theTask.launch()
theTask.waitUntilExit()
let taskData = taskOutput.fileHandleForReading.readDataToEndOfFile()
if let stringResult = NSString(data: taskData, encoding: NSUTF8StringEncoding) {
if stringResult != "ifconfig: interface en0 does not exist" {
let f = stringResult.rangeOfString("ether")
if f.location != NSNotFound {
let sub = stringResult.substringFromIndex(f.location + f.length)
let range = Range(start: advance(sub.startIndex, 1), end: advance(sub.startIndex, 18))
let result = sub.substringWithRange(range)
println(result)
}
}
}
这篇关于如何使用Swift从OS X获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!