in shenyu-common/src/main/java/org/apache/shenyu/common/utils/IpUtils.java [107:180]
public static String getHost(final String filterHost) {
String hostIp = null;
String pattern = filterHost;
// filter matching ip
if ("*".equals(filterHost) || "".equals(filterHost)) {
pattern = null;
} else if (Objects.nonNull(filterHost) && !filterHost.contains("*") && !isCompleteHost(filterHost)) {
pattern = filterHost + "*";
}
// if the progress works under docker environment
// return the host ip about this docker located from environment value
String dockerHostIp = System.getenv(SYSTEM_ENV_DOCKER_HOST_IP);
if (Objects.nonNull(dockerHostIp) && StringUtils.isNoneBlank(dockerHostIp)) {
return dockerHostIp;
}
// Traversal Network interface to scan all network interface
List<NetCard> ipv4Result = new ArrayList<>();
List<NetCard> ipv6Result = new ArrayList<>();
NetCard netCard;
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
final NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress inetAddress = addresses.nextElement();
if (Objects.nonNull(inetAddress) && !inetAddress.isLoopbackAddress()) {
if (inetAddress instanceof Inet4Address && isCompleteHost(inetAddress.getHostAddress())) {
netCard = new NetCard(inetAddress.getHostAddress(),
getName(networkInterface.getName()),
getNamePostfix(networkInterface.getName()),
Integer.parseInt(inetAddress.getHostAddress().split("\\.")[3]));
ipv4Result.add(netCard);
} else {
netCard = new NetCard(inetAddress.getHostAddress(),
getName(networkInterface.getName()),
getNamePostfix(networkInterface.getName()));
ipv6Result.add(netCard);
}
}
}
}
// sort ip
Comparator<NetCard> byNamePostfix = Comparator.comparing(NetCard::getNamePostfix);
Comparator<NetCard> byIpv4Postfix = (card1, card2) -> card2.getIpv4Postfix() - card1.getIpv4Postfix();
ipv4Result.sort(BY_NAME.thenComparing(byNamePostfix).thenComparing(byIpv4Postfix));
ipv6Result.sort(BY_NAME.thenComparing(byNamePostfix));
// prefer ipv4
if (!ipv4Result.isEmpty()) {
if (Objects.nonNull(pattern)) {
for (NetCard card : ipv4Result) {
if (ipMatch(card.getIp(), pattern)) {
hostIp = card.getIp();
break;
}
}
} else {
hostIp = ipv4Result.get(0).getIp();
}
} else if (!ipv6Result.isEmpty()) {
hostIp = ipv6Result.get(0).getIp();
}
// If failed to find,fall back to localhost
if (Objects.isNull(hostIp)) {
hostIp = InetAddress.getLocalHost().getHostAddress();
}
} catch (SocketException | UnknownHostException ignore) {
hostIp = LOCALHOST;
}
return hostIp;
}