Java获取机器IP

现象:在进行数据测试时,无意发现某台机器返回的IP不正确,其返回的为127.0.0.1。但其它机器均为正常。
该IP是通过InetAddress.getLocalHost()获取IP地址,查看该方法见其注释为:

* If there is a security manager, its * {@code checkConnect} method is called * with the local host name and {@code -1} * as its arguments to see if the operation is allowed. * If the operation is not allowed, an InetAddress representing * the loopback address is returned.

通过跟踪源码发现,是因为没有设置主机的hostname导致的。其解析的逻辑是根据localHostName来获取的,而localHostName在虚拟机里面默认为localhost.localdomain,而localhost.localdomain对应的则默认为127.0.0.1,
更改机器的hostname即可,其更改hostname方法如下:
hostnamectl set-hostname xxx

【Java获取机器IP】可以通过以下获取所有的IP(针对多网卡),并且对IP6地址过滤:
public static List getHostAddresses(Boolean filterIp6) { List result = new ArrayList<>(); try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) { continue; } Enumeration address = networkInterface.getInetAddresses(); while (address.hasMoreElements()) { InetAddress add = address.nextElement(); if (filterIp6 == null || filterIp6.booleanValue() == true) { if (add.getHostAddress().contains(":")) { continue; } } result.add(add.getHostAddress()); } } } catch (SocketException e) { e.printStackTrace(); } return result; }

    推荐阅读