简体   繁体   English

Java getHostAddress()返回VirtualBox IPv4地址

[英]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. 我正在使用Java在类中构建一个简单的方法,该方法将获取用户计算机的LAN IPv4地址。 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: 大多数情况下,这种方法很有效,但有一个例外......我收到的IP地址是我的VirtualBox以太网适配器的IPv4地址,正如我在命令提示符中输入ipconfig时所证明的那样:

在此输入图像描述

Here is the method that will grab the IP address: 这是获取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";
  }
}

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. 我想避免假设最终用户不会安装VirtualBox(或类似的东西)。

Thank you for your time. 感谢您的时间。

I think you need to look at the NetworkInterface class and seeing if it will help you exclude the virtual interface in this case: 我认为您需要查看NetworkInterface类,看看它是否有助于您在这种情况下排除虚拟接口:

    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. 我的设置上没有任何虚拟接口,所以我不知道它的工作情况有多好,但我希望能给你一个指针。

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. 根据Yishai建议使用NetworkInterface类,根据我的经验,isVirtual()没有区分VM网络适配器和“正常”网络适配器。

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. 但您可以使用NetworkInterface.getHardwareAddress()获取MAC地址,并进行一些模式匹配以猜测网络接口是否适用于虚拟机。 See this page for common virtual machine MAC address patterns. 有关常见虚拟机MAC地址模式,请参阅此页面

There is no guarantee this technique will work, as most VM software allows the user to explicitly set the MAC address for network adapters. 无法保证此技术可行,因为大多数VM软件允许用户显式设置网络适配器的MAC地址。 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. 但是,在大多数情况下,用户只需获取VM软件即可生成一个,因此这些模式应涵盖大多数情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM