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

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4