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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
public class IPUtils {
static final Logger logger = LoggerFactory.getLogger(IPUtils.class);
private static String localAddress = null;
/**
* <pre>
* 获取本机IPV4地址
* </pre>
*
* @return 如果无法获取 IP ips size为0
* @throws SocketException
*/
public static List<String> getIpAddress() {
List<String> ips = new ArrayList<String>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ipv4 = addresses.nextElement();
if (ipv4 instanceof Inet4Address) {
ips.add(ipv4.toString().replace("/", ""));
}
}
}
} catch (Exception e) {
logger.error("Get local IP error|{}", e.getMessage(), e);
}
logger.info("server ip|{}", ips);
return ips;
}
public static String getLocalAddress() {
if (!StringUtils.isEmpty(localAddress)) {
return localAddress;
}
List<String> ips = getIpAddress();
if (CollectionUtils.isEmpty(ips)) {
throw new RuntimeException("localAddress no found!");
}
return localAddress = ips.get(0);
}
}
获取IP地址
最新推荐文章于 2024-06-21 22:23:19 发布