127.0.0.1是回送适配器-这是对(有些恶意的)问题“我的IP地址是什么?”的正确答案。
问题是该问题有 多个 正确答案。
编辑:的文档
getLocalHost说:
如果有安全管理器,则使用本地主机名并以-1作为其参数来调用其checkConnect方法,以查看是否允许该操作。如果不允许该操作,则返回表示回送地址的InetAddress。
行为更改是否可能是由于权限更改引起的?
编辑:我相信这
NetworkInterface.getNetworkInterfaces就是您需要列举所有可能性的东西。这是一个示例,该示例不显示虚拟地址,但适用于“主要”接口:
import java.net.*;import java.util.*;public class Test{ public static void main(String[] args) throws Exception // Just for simplicity { for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { NetworkInterface iface = ifaces.nextElement(); System.out.println(iface.getName() + ":"); for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements(); ) { InetAddress address = addresses.nextElement(); System.out.println(" " + address); } } }}(我忘记
Enumeration<T>了直接使用该类型是多么糟糕!)
现在是我笔记本电脑上的结果:
lo: /127.0.0.1eth0: /169.254.148.66eth1:eth2:ppp0: /10.54.251.111
(我认为这不会 泄露 任何 非常 敏感的信息:)
如果您知道要使用哪个网络接口,请致电
NetworkInterface.getByName(...),然后查看该接口的地址(如上面的代码所示)。



