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