获取本机Ip算是比较常见的一个需求场景了,好比业务报警,可能就会带上出问题的机器IP,方便直接上去看日志定位问题,那么问题来了,如何获取机器IP呢?java
<!-- more -->git
如何获取机器Ip?若是了解InetAddress这个工具类,就很容易写出一个简单的工具类,以下github
public static String getLocalIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException(e); } }
上面的实现有问题么?服务器
固然没问题,拿我本机和阿里服务器执行一下,并无问题如实的输出了预期的IP工具
本机执行后截图以下:oop
阿里云机器执行后截图以下:学习
再问一句,那是否就真的没有问题了呢?测试
127.0.0.1
在虚拟机中执行时,就可能遇到这个问题,截图以下阿里云
作一点简单的改动,获取IpV4的地址,源码以下.net
/** * 直接根据第一个网卡地址做为其内网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); } }
再次测试,输出以下
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); } } }
一灰灰的我的博客,记录全部学习和工做中的博文,欢迎你们前去逛逛
尽信书则不如,已上内容,纯属一家之言,因我的能力有限,不免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激