废话不多说,直接上代码
public static String getLocalIP() throws Exception {
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLunixIp();
}
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
//获取lunix ip地址
private static String getLunixIp(){
String ip = "";
try {
Enumeration<?> e1 = NetworkInterface.getNetworkInterfaces();//获取多个网卡
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
if(("eth0").equals(ni.getName()) || ("ens33").equals(ni.getName())){//取“eth0”和“ens33”两个网卡
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()){
InetAddress ia = (InetAddress) e2.nextElement();
if(ia instanceof Inet6Address){
continue;
}
ip = ia.getHostAddress();
}
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ip;
}