1.背景
2.代码
package com.XXX.common.util;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
@Slf4j
public class HostUtil {
private static String ipAddress = null;
public static String getLocalIp() {
if (!StrUtil.isEmpty(ipAddress)) {
return ipAddress;
}
try {
ipAddress = getLocalIpAddress();
} catch (Exception e) {
log.error("获取IP异常: ", e);
}
return ipAddress;
}
private static String getLocalIpAddress() throws SocketException {
List<String> list = new ArrayList<>();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) {
list.add(address.getHostAddress());
}
}
}
return String.join(";", list);
}
}
完美!