修正取得外部IP的取得方式
This commit is contained in:
parent
9356be46ec
commit
864d181a16
@ -46,30 +46,7 @@ fun main() {
|
|||||||
|
|
||||||
runBlocking {
|
runBlocking {
|
||||||
println("-------- [ 開始更新 DNS ] --------")
|
println("-------- [ 開始更新 DNS ] --------")
|
||||||
val client = OkHttpClient()
|
val ipAddress = getPublicIPAddress()
|
||||||
val request: Request = Request.Builder()
|
|
||||||
.url("https://ifconfig.me")
|
|
||||||
.addHeader("User-Agent", "")
|
|
||||||
.method("GET", null)
|
|
||||||
.build()
|
|
||||||
val ipAddress = try {
|
|
||||||
val response = withContext(Dispatchers.IO) {
|
|
||||||
client.newCall(request).execute()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.isSuccessful) {
|
|
||||||
response.body()?.string() ?: run {
|
|
||||||
println("無法取得 WAN IP 位址")
|
|
||||||
return@runBlocking
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
} catch (e: IOException) {
|
|
||||||
null
|
|
||||||
} finally {
|
|
||||||
client.dispatcher().executorService().shutdown()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ipAddress != null) {
|
if (ipAddress != null) {
|
||||||
println("您目前的 WAN IP 位址為: $ipAddress")
|
println("您目前的 WAN IP 位址為: $ipAddress")
|
||||||
@ -143,3 +120,17 @@ private fun loadConfigFile(configRawText: String): Configure {
|
|||||||
println("欲更新的域名: $domain")
|
println("欲更新的域名: $domain")
|
||||||
return config
|
return config
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getPublicIPAddress(): String? {
|
||||||
|
return try {
|
||||||
|
val client = OkHttpClient()
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url("https://api64.ipify.org?format=text")
|
||||||
|
.build()
|
||||||
|
val response = client.newCall(request).execute()
|
||||||
|
response.body()?.string()?.trim()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user