3

Previously, when I was using openJDK 10, the below code gave my local IP address, however now it (inetAddress.getHostAddress()) always returns 127.0.1.1

import java.net.*;

class main {
    public static void main(String[] args) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println("IP Address:- " + inetAddress.getHostAddress());

    }
}

Additional information:

openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu219.04.1)
OpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu219.04.1, mixed mode, sharing)

I recently moved to ubuntu 19.04 from (18.04 LTS which had openJDK 10) [Not a virtual Machine],Is this due to firewall? In that case, how do I allow java through the firewall.

kalpaj agrawalla
  • 878
  • 1
  • 9
  • 19

1 Answers1

3

The result of that function depends on your system's configuration (which host is treated as "canonical" by your OS), which can be system and configuration dependent.

To find out internet addresses for your system, use NetworkInterface::getNetworkInterfaces(), as described eg. here: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html

In your case, what you want to do is probably something like this:

InetAddress theOneAddress = null;
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
    if (!netint.isLoopback()) {
        theOneAddress = Collections.list(netint.getInetAddresses()).stream().findFirst().orElse(null);
        if (theOneAddress != null) {
            break;
        }
    }
}
Piotr Wilkin
  • 3,446
  • 10
  • 18
  • 1
    Yes, but per documentation: "Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress." This is dependent eg. for Linux systems on what you have in /etc/hostname, which might have changed. You should not rely on undocumented, system-specific solutions to work over different OSes and/or Java versions. – Piotr Wilkin May 24 '19 at 12:58
  • Thanks! Are there any alternatives? [ to get my local ip ] I did see @steve-smith's answer, but I want a local way to do it. – kalpaj agrawalla May 24 '19 at 13:04
  • 2
    Basically, you want to use the abovementioned method to get all the interfaces, then filter out all that return `true` on `isLoopback()`. If you get a single one, that's the one you should use, if not, you should probably think on how to pick one (Java can't know which network interface is your primary one if you have more than one). – Piotr Wilkin May 24 '19 at 13:08
  • Thanks, will try this one, I didn't know there was a method called `isLoopbackAddress()` – kalpaj agrawalla May 24 '19 at 13:10