|
@@ -1,7 +1,18 @@
|
|
|
package com.ruoyi.common.utils.ip;
|
|
|
|
|
|
+import java.io.BufferedReader;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStreamReader;
|
|
|
import java.net.InetAddress;
|
|
|
+import java.net.URL;
|
|
|
import java.net.UnknownHostException;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.concurrent.Callable;
|
|
|
+import java.util.concurrent.ExecutionException;
|
|
|
+import java.util.concurrent.ExecutorService;
|
|
|
+import java.util.concurrent.Executors;
|
|
|
+import java.util.regex.Pattern;
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
import com.ruoyi.common.utils.ServletUtils;
|
|
|
import com.ruoyi.common.utils.StringUtils;
|
|
@@ -379,4 +390,51 @@ public class IpUtils
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 2024-12-16 fangqing 加入 获取外网IP地址
|
|
|
+ */
|
|
|
+ /**
|
|
|
+ * IP 地址校验的正则表达式
|
|
|
+ */
|
|
|
+ private static final Pattern IPV4_PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取 IP 地址的服务列表
|
|
|
+ */
|
|
|
+ private static final String[] IPV4_SERVICES = {
|
|
|
+ "http://checkip.amazonaws.com/",
|
|
|
+ "https://ipv4.icanhazip.com/",
|
|
|
+ "http://bot.whatismyipaddress.com/"
|
|
|
+ // and so on ...
|
|
|
+ };
|
|
|
+
|
|
|
+ public static String get() throws ExecutionException, InterruptedException {
|
|
|
+ List<Callable<String>> callables = new ArrayList<>();
|
|
|
+ for (String ipService : IPV4_SERVICES) {
|
|
|
+ callables.add(() -> get(ipService));
|
|
|
+ }
|
|
|
+
|
|
|
+ ExecutorService executorService = Executors.newCachedThreadPool();
|
|
|
+ try {
|
|
|
+ // 返回第一个成功获取的 IP
|
|
|
+ return executorService.invokeAny(callables);
|
|
|
+ } finally {
|
|
|
+ executorService.shutdown();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String get(String url) throws IOException {
|
|
|
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
|
|
|
+ String ip = in.readLine();
|
|
|
+ if (IPV4_PATTERN.matcher(ip).matches()) {
|
|
|
+ return ip;
|
|
|
+ } else {
|
|
|
+ throw new IOException("invalid IPv4 address: " + ip);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
}
|