127.0.0.1是环回适配器 - 这是对(有点malfomed)问题上完全正确的回应:“什么是我的IP地址?”
问题是,有多个该问题的正确答案。
编辑:为getLocalHost
文档说:
如果有安全管理器, checkConnect方法被调用的 本地主机名和-1作为 参数,看是否操作允许使用 。如果操作不是允许的 ,则表示返回地址为 的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.1
eth0:
/169.254.148.66
eth1:
eth2:
ppp0:
/10.54.251.111
(我不认为这放弃任何巨大敏感信息:)
如果您知道要使用哪个网络接口,请致电NetworkInterface.getByName(...)
,然后查看该接口的地址(如上面的代码所示)。
在上面的循环中,您也可以通过检查NetworkInterface#isLoopback()简单地跳过回送。 – omerkudat 2009-06-30 06:57:11