/**
* 获取本地 IP
* @return
*/
public static String getIp() {
try{
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
InetAddress ip = null;
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
if (bFindIP) {
break;
}
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
// --特定情况,可以考虑用ni.getName判断
// 遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
&& ip.getHostAddress().indexOf(":") == -1) {
bFindIP = true;
break;
}
}
}
if(ip!=null) {
return ip.getHostAddress();
} else {
return "127.0.0.1";
}
}
}catch(Exception e) {
return null;
}
}
/**
* 是否WINDOWS OS
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}