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
}
}