

Java 获取本机的外网 IP
source link: https://segmentfault.com/a/1190000040742660
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java 获取本机的外网 IP
通过 HTTP 访问第三方获取 IP 的服务接口获取本机的外网 IP,例如:
考虑到这些第三方接口不一定 100% 稳定,例如可能出现下线、错误、访问超时或太慢的情况,所以不能仅依赖其中之一。
下面提供一种方案,并发访问这些服务接口,并返回第一个成功的结果,也就是其中最快的一个返回结果。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.regex.Pattern; public class ExternalIPUtil { /** * 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); } } } }
线程池的 ExecutorService.invokeAny(callables)
方法用于并发执行多个线程,并拿到最快的执行成功的线程的返回值,只要有一个执行成功,其他失败的任务都会忽略。但是如果全部失败,例如本机根本就没有连外网,那么就会抛出 ExecutionException
异常。
关注我的公众号
Recommend
-
36
#!/bin/bashgen_size=$(df/|awk'/\//{print$4}')#提取根分区剩余空间mem_size=$(free|awk'/Mem/{print$4}')#提取内存剩余空间while:do#注意内存和磁盘提取的空间大小都是以Kb为单位if[$gen_size-le512000-a$mem_size-le1024000];thenmail-
-
54
现象在本机安装了一个Discuz!X3.4的论坛,其使用UCenter作为统一用户登录,在其应用管理页面,通信情况一直提示为“正在连接”: 原因关于这个问题,网上绝大多数的说法是nginx服务器在Windows上有问题,建议更换为Apache,我更换到Apache下,也确实是问题解决了,...
-
15
用Python获取本机网卡IP数据包 这几天用到了raw socket,用python写了些demo程序,这里记录下,也方便我以后查阅。 首...
-
7
linux 获取外网IP零一间2021.04.16 00:57:31字数 90阅读 15 为了隐私问题,以下IP最后两位使用"2x.9x"代替。 cip.cc
-
8
编程获取本机IPv4及IPv6地址 本文来自依云's...
-
8
V2EX › Android GitMind 怎么获取的本机号码? Aquamarine · 17 小时 52 分钟前 · 664...
-
15
vue项目获取本机局域网IP地址 2021-08-30 19:35:26 有时会有在局域网下通过 IP 地址访问 vue 项目的需求,记录下获取本机 IP 的方法。
-
10
DDNS可以根据内网ip获取外网ip进行域名解析吗? - OSCHINA - 中文开源技术交流社区 开源问答...
-
17
V2EX › 程序员 求推荐几个获取本机 IPv6 地址的 API 接口 LxnChan ·
-
3
LM Hash和NTML HashWindows操作系统中的密码由两部分加密组成,即LM Hash和NTML Hash。 LM Hash(LAN Manager Hash),本质为DES加密,密码不足14位用0补全。 自Server 2003之后,...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK