Java获取本机IP地址的方法(内网、公网)

2024-06-17 20:20

本文主要是介绍Java获取本机IP地址的方法(内网、公网),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

起因是公司一个springboot项目启动类打印了本机IP地址加端口号,方便访问项目页面,但是发现打印出来的不是“无线局域网”的ip而是“以太网适配器”ip,如下图所示

这样就导致后续本地起项目连接xxl-job注册节点的时候因为不在同个局域网下ping不通出问题,所以需要解决一下。

一、直接获取本机IP(会受到虚拟机干扰)

public static String getInterIP1() throws Exception {return InetAddress.getLocalHost().getHostAddress();
}

二、获取本机IP(排除虚拟机干扰)

public static InetAddress getLocalHostLANAddress() throws UnknownHostException {try {InetAddress candidateAddress = null;// 遍历所有的网络接口for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {NetworkInterface iface = (NetworkInterface) ifaces.nextElement();// 在所有的接口下再遍历IPfor (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址if (inetAddr.isSiteLocalAddress()) {// 如果是site-local地址,就是它了return inetAddr;} else if (candidateAddress == null) {// site-local类型的地址未被发现,先记录候选地址candidateAddress = inetAddr;}}}}if (candidateAddress != null) {return candidateAddress;}// 如果没有发现 non-loopback地址.只能用最次选的方案InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();if (jdkSuppliedAddress == null) {throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");}return jdkSuppliedAddress;} catch (Exception e) {UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);unknownHostException.initCause(e);throw unknownHostException;}}

三、获取本机公网IP

public static String getOutIP() {try {URL whatismyip = new URL("http://checkip.amazonaws.com");BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));String ip = in.readLine();return ip;} catch (Exception e) {}return "";
}

四、测试

public class IpTest {public static void main(String[] args) throws Exception {System.out.println("获取本机ip: " + getInterIP1());
//            System.out.println("getInterIP2: " + getInterIP2());System.out.println("获取本机ip(排除虚拟机干扰): " + String.valueOf(getLocalHostLANAddress()).substring(1));
//            System.out.println("getOutIPV4: " + getOutIPV4());System.out.println("获取本机公网ip: " + getOutIP());}public static String getInterIP1() throws Exception {return InetAddress.getLocalHost().getHostAddress();}public static InetAddress getLocalHostLANAddress() throws UnknownHostException {try {InetAddress candidateAddress = null;// 遍历所有的网络接口for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {NetworkInterface iface = (NetworkInterface) ifaces.nextElement();// 在所有的接口下再遍历IPfor (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址if (inetAddr.isSiteLocalAddress()) {// 如果是site-local地址,就是它了return inetAddr;} else if (candidateAddress == null) {// site-local类型的地址未被发现,先记录候选地址candidateAddress = inetAddr;}}}}if (candidateAddress != null) {return candidateAddress;}// 如果没有发现 non-loopback地址.只能用最次选的方案InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();if (jdkSuppliedAddress == null) {throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");}return jdkSuppliedAddress;} catch (Exception e) {UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);unknownHostException.initCause(e);throw unknownHostException;}}public static String getOutIP() {try {URL whatismyip = new URL("http://checkip.amazonaws.com");BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));String ip = in.readLine();return ip;
//                System.out.println("Public IP Address: " + ip);} catch (Exception e) {
//                System.out.println("Error occurred: " + e.getMessage());}return "";}}
获取本机ip: 172.17.16.1
获取本机ip(排除虚拟机干扰): 192.168.100.100
获取本机公网ip: 14.145.43.147

这里打印出来的便对应上前言命令行截图里的ip信息,然后公网ip对应的是百度搜索ip查到的公网ip地址 

五、手动禁用虚拟机排除干扰

除了用代码逻辑排除虚拟机干扰,我们也可以直接禁用电脑的虚拟机适配器。

步骤:

  1. win+R 
  2. devmgmt.msc 打开设备管理器
  3. 找到网络适配器-Hyper-V Virtual 开头的  右键禁用

此时win+R cmd 输入ipconfig,可以看到已经没有虚拟机ip了

此时java使用

InetAddress.getLocalHost().getHostAddress()

也可以获取到192.168开头的wifi地址了

这篇关于Java获取本机IP地址的方法(内网、公网)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1070412

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1