关于JAVA取本机ip的一些传说
1.获取windows下本机Ip地址方法
InetAddress.getLocalHost().getHostAddress()
2.获取Linux下本机Ip地址方法
用ifconfig看网卡:
这个时候就需要枚举多网卡判断了
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
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