Oliver Spryn
Oliver Spryn

Reputation: 17348

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.

Upvotes: 6

Views: 4188

Answers (2)

prunge
prunge

Reputation: 23248

Following on from Yishai's suggestion of using the NetworkInterface class, in my experience isVirtual() did not distinguish between VM network adapters and 'normal' ones.

But you can grab the MAC address using NetworkInterface.getHardwareAddress() and do some pattern matching to guess whether the network interface is for virtual machines. See this page for common virtual machine MAC address patterns.

There is no guarantee this technique will work, as most VM software allows the user to explicitly set the MAC address for network adapters. However, in the majority of cases, users will just get the VM software to generate one and so these patterns should cover the majority of cases.

Upvotes: 1

Yishai
Yishai

Reputation: 91871

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.

Upvotes: 6

Related Questions