public class ServerIpUtil {
private static final Logger logger = LoggerFactory.getLogger(ServerIpUtil.class);
/**
* 获取服务器IP
* @return
*/
public static String getServerIp() {
// 获取操作系统类型
String sysType = System.getProperties().getProperty("os.name");
if (sysType.toLowerCase().startsWith("win")) {
String localIP = null;
try {
// 如果是Windows系统,获取本地IP地址
localIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.error("未获取到Windows服务器IP", e);
}
return localIP;
} else {
// 兼容Linux
return getLinuxIp();
}
}
/**
* 获取Linux网络接口
* @return
*/
public static String getLinuxIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
return ia.getHostAddress();
}
}
}
} catch (SocketException e) {
logger.error("未获取到Linux服务器IP", e);
}
return null;
}
}