First, you may have several network interfaces, one of them is lo.
Second, you may have set both ipv4 and ipv6, i.e. have several ip addresses per network interface.
Thus, you need to define the ipaddress and net interface you will use and then make a filter. If you just take first address, you will get the same result as after Inet4Address.getLocalHost().getHostAddress()
Assume you want to get ipv4(ipv6) address for first not-loopback interface you find. Then, the following code gives the ip:
static InetAddress ip() throws SocketException {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
NetworkInterface ni;
while (nis.hasMoreElements()) {
ni = nis.nextElement();
if (!ni.isLoopback()/*not loopback*/ && ni.isUp()/*it works now*/) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
//filter for ipv4/ipv6
if (ia.getAddress().getAddress().length == 4) {
//4 for ipv4, 16 for ipv6
return ia.getAddress();
}
}
}
}
return null;
}
public static void main(String[] args) throws SocketException {
System.out.println(ip());
}