Trying to get InetAddress.getLocalHost.getHostAddress (Java / Scala) to return an external IP address

Thus, I had a problem using the InetAddress.getLocalHost.getHostAddressspecified machine to get the external IP address.

I really do it in Scala in a way - in the configuration file for Akka Remote Actors, by default it is used InetAddress.getLocalHost.getHostAddressto get the IP address of the machine, which I want, since I will deploy the participants to several machines. However, it seems that instead of an external IP address I want to return 127.0.0.1(since the remote participants must communicate with each other over the network).

The problem is that I cannot use any methods that I found on Google to get around this, since all of them seem to require setting up the code itself, whereas here I have no code to set up, DSL automatically uses InetAddress.getLocalHost.getHostAddress.

I read a few threads from a google search, that you can get around this by editing the host file or something like that? How to do it?

Thank! -kstruct

+3
source share
3 answers

You can use the NetworkInterface class.

In particular, use the static getNetworkInterfaces method to list all available network interfaces.

+3
source

/etc/hosts. "localhost" 127.0.0.1 IP- : - | , Linux .

+2

I got a partial solution if getLocalHost does not work. In this solution, the problem is that you must know the name of your network interface in order to match the real one. Maybe you can improve this code by removing the "virtual" devices and something else.

This is Scala code, but Java code is very similar

  def returnInterfaceAddress() : InetAddress = {
    var myInetAddress = InetAddress.getLocalHost
    val interfaces : util.Enumeration[NetworkInterface] = NetworkInterface.getNetworkInterfaces()
    while(interfaces.hasMoreElements){
      val inter = interfaces.nextElement()
      if(inter.getDisplayName() == "Realtek PCIe GBE Family Controller"){
        myInetAddress = inter.getInetAddresses().nextElement()
      }
    }
    myInetAddress
  }
0
source

All Articles