用java如何获得本机IP地址?

EternalCountry 2009-07-08 04:31:26
不要下面这种方法:这种方法得到的是127.0.0.1。
InetAddress addr = InetAddress.getLocalHost();
ip=addr.getHostAddress();
...全文
8214 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
myicezone 2010-03-06
  • 打赏
  • 举报
回复
真的是学习到了!回答问题就应该是像jiangnaisong这样,这样才真正学到东西。
woshixw86 2009-11-27
  • 打赏
  • 举报
回复
太好了 学习
baibinghere 2009-07-18
  • 打赏
  • 举报
回复
jiangnaisong,牛,应该用它这种方法。
liuqixun 2009-07-08
  • 打赏
  • 举报
回复
非常感谢
haowang21 2009-07-08
  • 打赏
  • 举报
回复

try {
java.net.InetAddress test = java.net.InetAddress.getByName("localhost") ;
System.out.println(test.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
一头头 2009-07-08
  • 打赏
  • 举报
回复
	public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostAddress());

}
// output 192.168.1.194
云上飞翔 2009-07-08
  • 打赏
  • 举报
回复
[Quote=引用楼主 EternalCountry 的帖子:]
不要下面这种方法:这种方法得到的是127.0.0.1。
InetAddress addr = InetAddress.getLocalHost();
ip=addr.getHostAddress();
[/Quote]
答:
1)在你的网卡处理激活状态下,用这种方式当然可以取到本机IP。
2)若不论网卡是否处理激活状态,想获取到本机所有的网卡的所有的IP(可能不只有一个网卡),则可用JDK6。0开始的
NetworkInterface.getNetworkInterfaces();就可获取到本机 所有的网卡的所有的IP(可能不只有一个网卡)了。
如:

Enumeration<NetworkInterface> e=NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}

运行结果:(我的本机)
name:lo (MS TCP Loopback interface) index: 1 addresses:
/127.0.0.1;

name:eth0 (VMware Virtual Ethernet Adapter for VMnet8) index: 2 addresses:
/192.168.92.1;

name:eth1 (VMware Virtual Ethernet Adapter for VMnet1) index: 3 addresses:
/192.168.211.1;

name:eth2 (Wireless LAN Card - ????ü??????ò?) index: 4 addresses:
/192.168.1.199;
一头头 2009-07-08
  • 打赏
  • 举报
回复
本机IP地址就是 127.0.0.1
你要什么

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧