java获取本机的外网IP地址(亲测有效)
2023-03-14 22:54:21 时间
获取本机的外网地址
如果下面正确,请留下您宝贵的赞
package untils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.*; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author CBeann * @create 2020-04-13 1:31 */ public class IPUntils { public static void main(String[] args) throws Exception { System.out.println(IPUntils.getInterIP1()); System.out.println(IPUntils.getInterIP2()); System.out.println(IPUntils.getOutIPV4()); } public static String getInterIP1() throws Exception { return InetAddress.getLocalHost().getHostAddress(); } public static String getInterIP2() throws SocketException { String localip = null;// 本地IP,如果没有配置外网IP则返回它 String netip = null;// 外网IP Enumeration<NetworkInterface> netInterfaces; netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; boolean finded = false;// 是否找到外网IP while (netInterfaces.hasMoreElements() && !finded) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> address = ni.getInetAddresses(); while (address.hasMoreElements()) { ip = address.nextElement(); if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP netip = ip.getHostAddress(); finded = true; break; } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP localip = ip.getHostAddress(); } } } if (netip != null && !"".equals(netip)) { return netip; } else { return localip; } } public static String getOutIPV4() { String ip = ""; String chinaz = "http://ip.chinaz.com"; StringBuilder inputLine = new StringBuilder(); String read = ""; URL url = null; HttpURLConnection urlConnection = null; BufferedReader in = null; try { url = new URL(chinaz); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8")); while ((read = in.readLine()) != null) { inputLine.append(read + " "); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } Pattern p = Pattern.compile("\<dd class\="fz24">(.*?)\<\/dd>"); Matcher m = p.matcher(inputLine.toString()); if (m.find()) { String ipstr = m.group(1); ip = ipstr; } return ip; } }
相关文章
- java求字符串型逻辑表达式的bool值
- 《Maven官方指南》指南第三方部署到远程仓库
- 再谈java的内存泄露
- JVM优化之调整大内存分页(LargePage)
- Java字符串的最大长度
- 剖析一个java对象初始化顺序问题
- java多线程编程的常见陷阱
- Java Memcached Client的Benchmark——xmemcached发布1.1.1
- CMS gc实践总结(纠正并发线程数)
- JAVA并发容器代码随读
- JRockit读书笔记I — Java代码的高效执行
- JAVA线程池代码浅析
- JVMTI开发教程之一个简单的Agent
- java 安全沙箱模型详解
- XMemcached 1.2.1正式发布
- Without SSH/JSP/Servlet,不走寻常路,Java可以更酷
- Java 异常处理
- Clojure的并发(一) Ref和STM
- Clojure的并发(二)Write Skew分析
- Clojure的并发(三)Atom、缓存和性能