Skip to content

Instantly share code, notes, and snippets.

@umpteenthdev
Created January 22, 2019 04:32
Show Gist options
  • Select an option

  • Save umpteenthdev/d09c56a279a49c9be00c338b837c0857 to your computer and use it in GitHub Desktop.

Select an option

Save umpteenthdev/d09c56a279a49c9be00c338b837c0857 to your computer and use it in GitHub Desktop.
How to check internet connection fastly
import java.net.InetSocketAddress
import java.net.Socket
class SocketConnectionChecker(
private val timeout: Int = 1000,
private val hostname: String = "8.8.8.8",
private val port: Port = Port.DNS
) {
fun isConnected(): Boolean =
try {
val address = InetSocketAddress(hostname, port.value)
Socket().use {
it.connect(address, timeout)
true
}
} catch (th: Throwable) {
false
}
enum class Port(val value: Int) {
DNS(53), HTTP(80)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment