-
Notifications
You must be signed in to change notification settings - Fork 5
/
Pinger.swift
63 lines (51 loc) · 1.5 KB
/
Pinger.swift
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
// Pinger.swift
// PingBar
//
// Created by Peter Kristensen on 20/11/2021.
//
import Foundation
class Pinger {
private var host: String
init(withHost: String) {
host = withHost
}
func pingOnce() -> TimeInterval {
let task = Process()
let date = Date()
task.launchPath = "/sbin/ping"
task.arguments = [
"-o",
"-c", "1",
"-q", host
]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
let termStatus = task.terminationStatus
let hd = pipe.fileHandleForReading
let data = hd.readDataToEndOfFile()
let string = String(data: data, encoding: .utf8)
if termStatus != 0 {
print("infinity: %d", termStatus)
return -1
}
var dt = Date().timeIntervalSince(date)
string?.enumerateLines(invoking: { str, stop in
if str.hasPrefix("round-trip") {
stop = true
let comps = str.components(separatedBy: CharacterSet(charactersIn: "/ "))
for obj in comps {
let obj = obj as NSString
let d = TimeInterval(obj.floatValue)
if d != 0.0 {
dt = d / 1000.0
break
}
}
}
})
return dt
}
}