When ipType is IPv6 but there's no IPv6 found, find IPv4(Fixes gh-2802) (#2810)

* When ipType is IPv6 but there's no IPv6 found, find IPv4(Fixes gh-2802)

* correct findIPv6Address()

* correct import
pull/2820/head
pandaapo 2 years ago committed by GitHub
parent 3ba918ce09
commit f112981a0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -166,6 +166,8 @@ public class NacosDiscoveryProperties {
/**
* choose IPv4 or IPv6,if you don't set it will choose IPv4.
* When IPv6 is chosen but no IPv6 can be found, system will automatically find IPv4 to ensure there is an
* available service address.
*/
private String ipType = "IPv4";
@ -260,6 +262,10 @@ public class NacosDiscoveryProperties {
}
else if ("IPv6".equalsIgnoreCase(ipType)) {
ip = inetIPv6Utils.findIPv6Address();
if (StringUtils.isEmpty(ip)) {
log.warn("There is no available IPv6 found. Spring Cloud Alibaba will automatically find IPv4.");
ip = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
}
}
else {
throw new IllegalArgumentException(

@ -29,6 +29,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.alibaba.cloud.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -66,13 +67,7 @@ public class InetIPv6Utils implements Closeable {
if (address != null) {
return this.convertAddress(address);
}
else {
InetUtils.HostInfo hostInfo = new InetUtils.HostInfo();
this.properties.setDefaultIpAddress("0:0:0:0:0:0:0:1");
hostInfo.setHostname(this.properties.getDefaultHostname());
hostInfo.setIpAddress(this.properties.getDefaultIpAddress());
return hostInfo;
}
return null;
}
public InetAddress findFirstNonLoopbackIPv6Address() {
@ -111,26 +106,30 @@ public class InetIPv6Utils implements Closeable {
catch (IOException e) {
log.error("Cannot get first non-loopback address", e);
}
if (address != null) {
return address;
}
try {
return InetAddress.getLocalHost();
}
catch (UnknownHostException e) {
log.warn("Unable to retrieve localhost");
if (address == null) {
try {
InetAddress localHost = InetAddress.getLocalHost();
if (localHost instanceof Inet6Address && !localHost.isLoopbackAddress()
&& isPreferredAddress(localHost)) {
address = localHost;
}
}
catch (UnknownHostException e) {
log.warn("Unable to retrieve localhost");
}
}
return null;
return address;
}
public String findIPv6Address() {
String ip = findFirstNonLoopbackHostInfo().getIpAddress();
int index = ip.indexOf('%');
ip = index > 0 ? ip.substring(0, index) : ip;
return iPv6Format(ip);
InetUtils.HostInfo hostInfo = findFirstNonLoopbackHostInfo();
String ip = hostInfo != null ? hostInfo.getIpAddress() : "";
if (!StringUtils.isEmpty(ip)) {
int index = ip.indexOf('%');
ip = index > 0 ? ip.substring(0, index) : ip;
return iPv6Format(ip);
}
return ip;
}
public String iPv6Format(String ip) {

Loading…
Cancel
Save