Java中Linux环境如何正确的获取本机ip地址方式
背景
当我们使用以下代码获取本机Ip时,明明本地测试成功,上到测试环境ip却不正确
InetAddress localHost = InetAddress.getLocalHost();
在Windows上测试
192.176.113.170
在Linux上测试
127.0.0.1
原因
在Linux环境中,因为它就是简单的读取/etc/hosts
的内容,所以它默认返回的是127.0.0.1
非常的不靠谱,因此本方法十分不建议在生产上使用。
(/etc/hosts
的第一行一般均是:127.0.0.1 localhost
,所以返回值是127.0.0.1
(倘若你把第一行改为127.1.1.1 localhost
,那么它的返回值就是127.1.1.1
了))
解决
public static void main(String[] args) throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); System.out.println(localHost.getHostAddress()); System.out.println("----------------下面才是正确的获取方式----------------"); localHost = getLocalHostExactAddress(); System.out.println(localHost.getHostAddress()); // System.out.println(localHost.getHostName()); } public static InetAddress getLocalHostExactAddress() { try { InetAddress candidateAddress = null; Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface iface = networkInterfaces.nextElement(); // 该网卡接口下的ip会有多个,也需要一个个的遍历,找到自己所需要的 for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) { InetAddress inetAddr = inetAddrs.nextElement(); // 排除loopback回环类型地址(不管是IPv4还是IPv6 只要是回环地址都会返回true) if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 就是我们要找的 // ~~~~~~~~~~~~~绝大部分情况下都会在此处返回你的ip地址值~~~~~~~~~~~~~ return inetAddr; } // 若不是site-local地址 那就记录下该地址当作候选 if (candidateAddress == null) { candidateAddress = inetAddr; } } } } // 如果出去loopback回环地之外无其它地址了,那就回退到原始方案吧 return candidateAddress == null ? InetAddress.getLocalHost() : candidateAddress; } catch (Exception e) { e.printStackTrace(); } return null; }
通过这种方法获取到ip不管是在Windows上还是linux上都是正确的主机ip!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix