From fa42710ae899f49b50bd02a6f53b30d3c0428423 Mon Sep 17 00:00:00 2001 From: Robinson Date: Tue, 6 Apr 2021 12:59:06 +0200 Subject: [PATCH] Added getPublicIpViaHttp() --- src/dorkbox/netUtil/IP.kt | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/dorkbox/netUtil/IP.kt b/src/dorkbox/netUtil/IP.kt index b394529..99c9cb8 100644 --- a/src/dorkbox/netUtil/IP.kt +++ b/src/dorkbox/netUtil/IP.kt @@ -1,7 +1,10 @@ package dorkbox.netUtil import dorkbox.netUtil.Common.logger +import java.io.BufferedReader +import java.io.InputStreamReader import java.net.* +import java.util.regex.Pattern /** * A class that holds a number of network-related constants, also from: @@ -237,6 +240,48 @@ object IP { ?: throw UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.") } + /** + * This will retrieve your IP address via an HTTP server. + * + * **NOTE: Can optionally use DnsClient.getPublicIp() instead. It's much faster and more reliable as it uses DNS.** + * + * @return the public IP address if found, or null if it didn't find it + */ + fun getPublicIpViaHttp(): String? { + // method 1: use DNS servers + // dig +short myip.opendns.com @resolver1.opendns.com + + // method 2: use public http servers + // @formatter:off + val websites = arrayOf( + "http://ip.dorkbox.com/", + "http://checkip.dyndns.com/", + "http://checkip.dyn.com/", + "http://curlmyip.com/", + "http://ipecho.net/plain", + "http://icanhazip.com/") + // @formatter:on + + // loop, since they won't always work. + for (i in websites.indices) { + try { + val autoIP = URL(websites[i]) + val `in` = BufferedReader(InputStreamReader(autoIP.openStream())) + val response = `in`.readLine() + .trim { it <= ' ' } + `in`.close() + val pattern = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b") + val matcher = pattern.matcher(response) + if (matcher.find()) { + return matcher.group() + .trim { it <= ' ' } + } + } catch (ignored: java.lang.Exception) { + } + } + return null + } + /** * Creates an byte[] based on an ipAddressString. No error handling is performed here. */