Last active
June 3, 2023 17:13
-
-
Save hguandl/284ae3b032587eda2958e31383e5135b to your computer and use it in GitHub Desktop.
Detect network changes on macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// NetworkChangeDetector | |
// | |
// Created by Hao Guan on 2021/8/30. | |
// | |
import Foundation | |
import Network | |
import CoreWLAN | |
// 对于执行 shell 命令进行简单的封装 | |
@discardableResult | |
func shell(prog: String, args: [String]) -> Bool { | |
let task = Process() | |
task.launchPath = prog | |
task.arguments = args | |
task.launch() | |
return task.isRunning | |
} | |
// 创建网络状态变化检测 | |
let monitor = NWPathMonitor() | |
monitor.pathUpdateHandler = { path in | |
// 无网络 | |
if path.status == .unsatisfied { | |
print("No network.") | |
return | |
} | |
// 已联网的接口 | |
print("Online interfaces: \(path.availableInterfaces)") | |
var first = true | |
for iface in path.availableInterfaces { | |
let msg: String | |
// 以太网,获取网关 | |
if iface.type == .wiredEthernet { | |
msg = "\(iface.name): Ethernet with \(path.gateways)." | |
// Wi-Fi,获取 SSID | |
} else if iface.type == .wifi { | |
let client = CWWiFiClient().interface(withName: iface.name) | |
let ssid = client?.ssid() ?? "<No SSID>" | |
msg = "\(iface.name): Wi-Fi called \(ssid)" | |
} else { | |
msg = "\(iface.name) other type." | |
} | |
// 默认接口 | |
if first { | |
print("* \(msg)") | |
first = false | |
} else { | |
print(" \(msg)") | |
} | |
} | |
// 执行脚本 | |
// shell(prog: "/bin/ls", args: ["/"]) | |
} | |
// 开始监听网络变化 | |
let queue = DispatchQueue.global(qos: .background) | |
monitor.start(queue: queue) | |
// 阻塞主线程,让程序在后台持续运行 | |
let group = DispatchGroup() | |
group.enter() | |
let _ = group.wait(timeout: .distantFuture) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment