获取本机Ip算是比较常见的一个需求场景了,比如业务报警,可能就会带上出问题的机器IP,方便直接上去看日志定位问题,那么问题来了,如何获取机器IP呢?
I. IpUtil工具类
1. 基本方法
如何获取机器Ip?如果了解InetAddress这个工具类,就很容易写出一个简单的工具类,如下
public static String getLocalIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } 复制代码
上面的实现有问题么?
当然没问题,拿我本机和阿里服务器执行一下,并没有问题如实的输出了预期的IP
本机执行后截图如下:
阿里云机器执行后截图如下:
再问一句,那是否就真的没有问题了呢?
- 在某些情况下,可能返回的是
127.0.0.1
在虚拟机中执行时,就可能遇到这个问题,截图如下
2. 进阶版
做一点简单的改动,获取IpV4的地址,源码如下
/** * 直接根据第一个网卡地址作为其内网ipv4地址,避免返回 127.0.0.1 * * @return */ public static String getLocalIpByNetcard() { try { for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) { NetworkInterface item = e.nextElement(); for (InterfaceAddress address : item.getInterfaceAddresses()) { if (item.isLoopback() || !item.isUp()) { continue; } if (address.getAddress() instanceof Inet4Address) { Inet4Address inet4Address = (Inet4Address) address.getAddress(); return inet4Address.getHostAddress(); } } } return InetAddress.getLocalHost().getHostAddress(); } catch (SocketException | UnknownHostException e) { throw new RuntimeException(e); } } 复制代码
再次测试,输出如下
3. 完整工具类
import java.net.*; import java.util.Enumeration; public class IpUtil { public static final String DEFAULT_IP = "127.0.0.1"; /** * 直接根据第一个网卡地址作为其内网ipv4地址,避免返回 127.0.0.1 * * @return */ public static String getLocalIpByNetcard() { try { for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) { NetworkInterface item = e.nextElement(); for (InterfaceAddress address : item.getInterfaceAddresses()) { if (item.isLoopback() || !item.isUp()) { continue; } if (address.getAddress() instanceof Inet4Address) { Inet4Address inet4Address = (Inet4Address) address.getAddress(); return inet4Address.getHostAddress(); } } } return InetAddress.getLocalHost().getHostAddress(); } catch (SocketException | UnknownHostException e) { throw new RuntimeException(e); } } public static String getLocalIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } }