85 lines
2.2 KiB
Kotlin
85 lines
2.2 KiB
Kotlin
![]() |
package dorkbox.netUtil.ping
|
||
|
|
||
|
import dorkbox.executor.Executor
|
||
|
import dorkbox.netUtil.Common
|
||
|
import org.slf4j.LoggerFactory
|
||
|
import java.io.IOException
|
||
|
import java.time.Duration
|
||
|
|
||
|
/**
|
||
|
*
|
||
|
*/
|
||
|
class Ping {
|
||
|
companion object {
|
||
|
private val logger = LoggerFactory.getLogger(Ping::class.java.simpleName)
|
||
|
}
|
||
|
|
||
|
private val count = 4
|
||
|
private val host = "1.1.1.1"
|
||
|
private val waitTime = Duration.ofSeconds(4)
|
||
|
private val deadline: Duration? = null
|
||
|
private val ttl: Short? = null
|
||
|
|
||
|
@Throws(IOException::class)
|
||
|
fun run(): PingResult {
|
||
|
val ping = Executor()
|
||
|
.command("ping")
|
||
|
|
||
|
if (Common.OS_WINDOWS) {
|
||
|
ping.addCommand("-n")
|
||
|
ping.addCommand("$count")
|
||
|
}
|
||
|
else {
|
||
|
ping.addCommand("-q")
|
||
|
ping.addCommand("-c $count")
|
||
|
}
|
||
|
|
||
|
if (waitTime != null) {
|
||
|
when {
|
||
|
Common.OS_MAC -> {
|
||
|
ping.addCommand("-W " + waitTime.toMillis())
|
||
|
}
|
||
|
Common.OS_WINDOWS -> {
|
||
|
ping.addCommand("-w " + waitTime.toMillis())
|
||
|
}
|
||
|
else -> {
|
||
|
ping.addCommand("-W " + waitTime.seconds)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (deadline != null) {
|
||
|
when {
|
||
|
Common.OS_MAC -> {
|
||
|
ping.addCommand("-t " + deadline.seconds)
|
||
|
}
|
||
|
Common.OS_WINDOWS -> {
|
||
|
logger.info("Deadline is not supported on Windows")
|
||
|
}
|
||
|
else -> {
|
||
|
ping.addCommand("-w " + deadline.seconds)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (ttl != null) {
|
||
|
when {
|
||
|
Common.OS_MAC -> {
|
||
|
ping.addCommand("-m $ttl")
|
||
|
}
|
||
|
Common.OS_WINDOWS -> {
|
||
|
ping.addCommand("-i $ttl")
|
||
|
}
|
||
|
else -> {
|
||
|
ping.addCommand("-t $ttl")
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
ping.command("ping $host")
|
||
|
|
||
|
// wait for it to finish running
|
||
|
val output: String = ping.readOutput().startAsShellBlocking().output.utf8()
|
||
|
return PingResultBuilder.fromOutput(output)
|
||
|
}
|
||
|
}
|