输出结果:
实现代码:
java
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
public class ServerIPUtils {
public static void main(String[] args) {
System.out.println(getCombinedIp());
System.out.println(getExternalIp());
System.out.println(getInternalIp());
}
/**
* 获取拼接的IP地址(外网_内网)
* 如果外网IP为空或获取失败,则只返回内网IP
* @return 拼接后的IP地址
*/
public static String getCombinedIp() {
String externalIp = getExternalIp();
String internalIp = getInternalIp();
// 如果外网IP为空或为unknown,则只返回内网IP
if (externalIp == null || externalIp.isEmpty()) {
return internalIp;
}
// 否则返回 外网IP_内网IP 的格式
return externalIp + "_" + internalIp;
}
/**
* 获取内网IP地址
* @return 内网IP地址
*/
public static String getInternalIp() {
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 address = addresses.nextElement();
String ip = address.getHostAddress();
// 跳过IPv6地址和回环地址
if (ip.contains(":") || ip.startsWith("127.")) {
continue;
}
// 返回第一个有效的私有IP地址
if (isValidIpAddress(ip)) {
return ip;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "127.0.0.1"; // 默认返回本地回环地址
}
/**
* 获取外网IP地址
* @return 外网IP地址
*/
public static String getExternalIp() {
// 定义多个获取公网IP的服务URL
String[] urls = {
"http://ifconfig.me",
"http://ifconfig.co",
"http://icanhazip.com",
"http://ident.me",
"http://whatismyip.akamai.com"
};
// 尝试每个服务直到成功获取IP
for (String url : urls) {
try {
HttpResponse response = HttpRequest.get(url)
.timeout(5000)
.execute();
// 检查响应状态码和内容
if (response.getStatus() == 200 && response.body() != null) {
String ip = response.body().trim();
if (!ip.isEmpty() && isValidIpAddress(ip)) {
return ip;
}
}
} catch (Exception e) {
// 继续尝试下一个服务
continue;
}
}
return null;
}
// 验证IP地址格式是否有效
private static boolean isValidIpAddress(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
String[] parts = ip.split("\\.");
if (parts.length != 4) {
return false;
}
for (String part : parts) {
try {
int num = Integer.parseInt(part);
if (num < 0 || num > 255) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
}
return true;
}
}
另外导入hutool包
XML
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.8.20</version>
</dependency>