Search code examples
javaip-addressvirtualboxlanipv4

Java getHostAddress() Returning VirtualBox IPv4 Address


I am using Java to build a simple method within a class that will grab the LAN IPv4 address of the user's machine. For the most part this works well, with one exception... the IP address I get back is the IPv4 address of my VirtualBox Ethernet adapter, as is proven when I enter ipconfig into the command prompt:

enter image description here

Here is the method that will grab the IP address:

import java.net.InetAddress;
import java.net.UnknownHostException;

...

private String getIP() {
  try {
    return InetAddress.getLocalHost().getHostAddress();
  } catch (UnknownHostException e) {
    return "0.0.0.0";
  }
}

Could anyone please show me how to work around this? I would like to avoid assuming that the end-user will not have VirtualBox (or something of the like) installed.

Thank you for your time.


Solution

  • I think you need to look at the NetworkInterface class and seeing if it will help you exclude the virtual interface in this case:

        for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            //Perhaps networkInterface.isVirtual() will help you identify the correct one?
        }
    

    I don't have any virtual interfaces on my setup, so I can't tell how well it works, but I hope that gives you a pointer.