Java getHostAddress()返回VirtualBox IPv4地址

Oli*_*ryn 3 java lan virtualbox ip-address ipv4

我正在使用Java在类中构建一个简单的方法,该方法将获取用户计算机的LAN IPv4地址.在大多数情况下,这种方法很有效,但有一个例外......我得到的IP地址是我的VirtualBox以太网适配器的IPv4地址,我在进入ipconfig命令提示符时已经证明了这一点:

在此输入图像描述

这是获取IP地址的方法:

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

...

private String getIP() {
  try {
    return InetAddress.getLocalHost().getHostAddress();
  } catch (UnknownHostException e) {
    return "0.0.0.0";
  }
}
Run Code Online (Sandbox Code Playgroud)

有谁可以告诉我如何解决这个问题?我想避免假设最终用户不会安装VirtualBox(或类似的东西).

感谢您的时间.

Yis*_*hai 5

我认为您需要查看NetworkInterface类,看看它是否有助于您在这种情况下排除虚拟接口:

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

我的设置上没有任何虚拟接口,所以我无法分辨它的工作情况,但我希望能给你一个指针.