通常,我们都是用以下代码来获取本地ip地址的
- InetAddress.getLocalHost().getHostAddress()
InetAddress.getLocalHost().getHostAddress()
这种方法在linux却只能取到127.0.0.1这个让人无奈的地址。。。这简直是让人不能忍受的啊。。。这种地址不用获取,我们谁不知道。。。
在网上搜索了很多,发现说这个问题的并不多,所以,我把找到的一段代码分享给大家。。。当然这段代码需要jdk1.5以上版本
- Enumeration<NetworkInterface> netInterfaces = null;
- try {
- netInterfaces = NetworkInterface.getNetworkInterfaces();
- while (netInterfaces.hasMoreElements()) {
- NetworkInterface ni = netInterfaces.nextElement();
- System.out.println("DisplayName:" + ni.getDisplayName());
- System.out.println("Name:" + ni.getName());
- Enumeration<InetAddress> ips = ni.getInetAddresses();
- while (ips.hasMoreElements()) {
- System.out.println("IP:"
- + ips.nextElement().getHostAddress());
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
System.out.println("IP:"
+ ips.nextElement().getHostAddress());
}
}
} catch (Exception e) {
e.printStackTrace();
}
这段代码会输出计算机中所有设备的ip,找需要的用吧,呵呵
转自:http://kaza.javaeye.com/blog/169889