LoginSignup
1
3

More than 3 years have passed since last update.

Swift:macのネットワーク上り下りスピードを取得する

Last updated at Posted at 2019-12-15
  • CapabilitiesIncoming Connections (Server)またはOutgoing Connections (Client)にチェックを入れる
class Network {

    private var lastUpBytes: Int?
    private var lastDownBytes: Int?

    // interval秒ごとのスピード
    func speed(interval: Int) {
        let process = Process()
        process.launchPath = "/usr/bin/env"
        process.arguments = ["netstat", "-bdI", "en0"]

        let pipe = Pipe()
        process.standardOutput = pipe
        process.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        guard var commandOutput = String(data: data, encoding: .utf8) else {
            return
        }
        commandOutput = commandOutput.lowercased()
        let lines = commandOutput.components(separatedBy: .newlines)
        let stats = lines[1].components(separatedBy: .whitespaces).compactMap({ (str) -> String? in
            return str.isEmpty ? nil : str
        })
        let upBytes = Int(stats[9]) ?? 0
        let downBytes = Int(stats[6]) ?? 0
        var upSpeed: Int = 0
        var downSpeed: Int = 0
        if lastDownBytes != nil && lastUpBytes != nil {
            upSpeed = (upBytes - lastUpBytes!) / interval
            downSpeed = (downBytes - lastDownBytes!) / interval
        }
        lastUpBytes = upBytes
        lastDownBytes = downBytes

        Swift.print("Upload: \(convert(byte: Double(upSpeed)))")
        Swift.print("Download: \(convert(byte: Double(downSpeed)))")
    }

    private func convert(byte: Double) -> String {
        let KB: Double = 1024
        let MB: Double = pow(KB, 2)
        let GB: Double = pow(KB, 3)
        var str = ""
        if GB <= byte {
            str = String((10 * byte / GB).rounded() / 10) + " GB/s"
        } else if MB <= byte {
            str = String((10 * byte / MB).rounded() / 10) + " MB/s"
        } else {
            str = String((10 * byte / KB).rounded() / 10) + " KB/s"
        }
        return str
    }

}

参考

iglance/iGlance

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3