From 864d181a16cf6435b9dff7566ebdb161ac1641c6 Mon Sep 17 00:00:00 2001 From: Raymond Yang Date: Tue, 25 Feb 2025 10:49:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8F=96=E5=BE=97=E5=A4=96?= =?UTF-8?q?=E9=83=A8IP=E7=9A=84=E5=8F=96=E5=BE=97=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/kotlin/Main.kt | 39 +++++++++++++++------------------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt index 65782bc..be56191 100644 --- a/src/main/kotlin/Main.kt +++ b/src/main/kotlin/Main.kt @@ -46,30 +46,7 @@ fun main() { runBlocking { println("-------- [ 開始更新 DNS ] --------") - val client = OkHttpClient() - 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() - } + val ipAddress = getPublicIPAddress() if (ipAddress != null) { println("您目前的 WAN IP 位址為: $ipAddress") @@ -142,4 +119,18 @@ private fun loadConfigFile(configRawText: String): Configure { println("CF 權杖: $token") println("欲更新的域名: $domain") 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 + } } \ No newline at end of file