您的位置:首页 > 编程语言 > Java开发

关于JAVA取本机ip的一些传说

2013-12-31 11:13 267 查看


关于JAVA取本机ip的一些传说

参考:/article/7487820.html
http://webcache.googleusercontent.com/search?q=cache:nX6WhHN0qVoJ:sw1982.iteye.com/blog/854892+isSiteLocalAddress&cd=1&hl=zh-CN&ct=clnk&gl=cn

1.获取windows下本机Ip地址方法

InetAddress.getLocalHost().getHostAddress()


2.获取Linux下本机Ip地址方法

用ifconfig看网卡:



这个时候就需要枚举多网卡判断了

Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();


然后结合IP4的地址段做区分,主要利用以下两个方法:

ip.isSiteLocalAddress() && !ip.isLoopbackAddress()


完整方法:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
* User: hangyushen Date: 13-12-31 Time: 上午10:33
*/
public class MainApp {
public static void main(String args[]) throws UnknownHostException {
// windows下获取本机ip地址方法在linux系统下的输出
System.out.println("+++++++++++++++++++++" + InetAddress.getLocalHost().getHostAddress());

InetAddress ip = null;
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();
// 输出计算机中所有设备的ip
while (ips.hasMoreElements()) {
System.out.println("IP:" + ips.nextElement().getHostAddress());
ip = ips.nextElement();
// 查找需要的本地ip
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1 ) {
System.out.println("--------------------------" + ip.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


输出结果:

+++++++++++++++++++++127.0.1.1
DisplayName:wlan0
Name:wlan0
IP:fe80:0:0:0:e84:dcff:fea6:e52e%3
--------------------------192.168.132.205
DisplayName:eth0
Name:eth0
IP:fe80:0:0:0:f21f:afff:fe2a:3511%2
--------------------------192.168.112.129
DisplayName:lo
Name:lo
IP:0:0:0:0:0:0:0:1%1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: