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