IPv6 support (#3773)

* IPv6 support

* AddressServerParamCheckUtil 合并到 IpUtil 及一些修改

* 解决魔法值

* 修改隐患

* 调整使用了类似 ip.indexOf(":") 查找是否有端口的地方的逻辑, 一些 ":" 替换为常量

* 删除无用测试

* IpUtil 改名 为 IPUtil, 涉及IP的相关方法名修改,涉及到的调用修改,检测IP的地方调用的isIPv4改为isIP. 修改涉及IP的字段长度及相关升级更新的sql

* no message

* no message

* no message

* no message

* 获取本机IP时,如果本机IP是IPv6并且包含网卡信息(V6地址中最后面的百分号和百分号后面的内容)则去除网卡信息

* 解决 AvoidComplexConditionRule(请不要在条件中使用复杂的表达式)

* 移除无用代码

* 添加注释

* 调整code style, 调整获取本机IP的逻辑
This commit is contained in:
邪影oO 2020-11-05 20:15:06 +08:00 committed by GitHub
parent 6ddfa3e997
commit 538509502f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 506 additions and 265 deletions

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instance;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -85,14 +86,11 @@ public class AddressServerGeneratorManager {
} }
private String[] generateIpAndPort(String ip) { private String[] generateIpAndPort(String ip) {
String[] result = IPUtil.splitIPPortStr(ip);
int index = ip.indexOf(AddressServerConstants.IP_PORT_SEPARATOR); if (result.length != IPUtil.SPLIT_IP_PORT_RESULT_LENGTH) {
if (index != -1) { return new String[] {result[0], String.valueOf(AddressServerConstants.DEFAULT_SERVER_PORT)};
return new String[] {ip.substring(0, index), ip.substring(index + 1)};
} }
return result;
return new String[] {ip, String.valueOf(AddressServerConstants.DEFAULT_SERVER_PORT)};
} }
/** /**

View File

@ -38,11 +38,6 @@ public interface AddressServerConstants {
*/ */
String DEFAULT_PRODUCT = "nacos"; String DEFAULT_PRODUCT = "nacos";
/**
* the separator between ip and port.
*/
String IP_PORT_SEPARATOR = ":";
/** /**
* the separator for service name between raw service name and group. * the separator for service name between raw service name and group.
*/ */

View File

@ -20,9 +20,9 @@ import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.address.component.AddressServerManager; import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants; import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.address.misc.Loggers; import com.alibaba.nacos.address.misc.Loggers;
import com.alibaba.nacos.address.util.AddressServerParamCheckUtil;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker; import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
@ -87,8 +87,8 @@ public class AddressServerClusterController {
clusterObj.setHealthChecker(new AbstractHealthChecker.None()); clusterObj.setHealthChecker(new AbstractHealthChecker.None());
serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj); serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj);
String[] ipArray = addressServerManager.splitIps(ips); String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = AddressServerParamCheckUtil.checkIps(ipArray); String checkResult = IPUtil.checkIPs(ipArray);
if (AddressServerParamCheckUtil.CHECK_OK.equals(checkResult)) { if (IPUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray); .generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
for (Instance instance : instanceList) { for (Instance instance : instanceList) {
@ -143,8 +143,8 @@ public class AddressServerClusterController {
} else { } else {
// delete specified ip list // delete specified ip list
String[] ipArray = addressServerManager.splitIps(ips); String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = AddressServerParamCheckUtil.checkIps(ipArray); String checkResult = IPUtil.checkIPs(ipArray);
if (AddressServerParamCheckUtil.CHECK_OK.equals(checkResult)) { if (IPUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray); .generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false,

View File

@ -1,67 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.address.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides a unified tool class for address server parameter verification.
*
* @author pbting
* @date 2019-06-19 11:19 AM
* @since 1.1.0
*/
public class AddressServerParamCheckUtil {
public static final String CHECK_OK = "ok";
public static final String ILLEGAL_IP_PREFIX = "illegal ip: ";
private static final String IP_REGEX = "(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})(\\.(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})){3}";
private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX);
/**
* Check ips.
*
* @param ips ips
* @return 'ok' if check passed, otherwise illegal ip
*/
public static String checkIps(String... ips) {
if (ips == null || ips.length == 0) {
return CHECK_OK;
}
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
Matcher matcher = IP_PATTERN.matcher(ip);
if (matcher.matches()) {
continue;
}
illegalResponse.append(ip + ",");
}
if (illegalResponse.length() == 0) {
return CHECK_OK;
}
return ILLEGAL_IP_PREFIX + illegalResponse.substring(0, illegalResponse.length() - 1);
}
}

View File

@ -16,17 +16,17 @@
package com.alibaba.nacos.address; package com.alibaba.nacos.address;
import com.alibaba.nacos.address.util.AddressServerParamCheckUtil; import com.alibaba.nacos.common.utils.IPUtil;
import org.junit.Test; import org.junit.Test;
public class ParamCheckUtilTests { public class ParamCheckUtilTests {
@Test @Test
public void checkIps() { public void checkIPs() {
String[] ips = {"127.0.0.1"}; String[] ips = {"127.0.0.1"};
System.out.println(AddressServerParamCheckUtil.checkIps(ips)); System.out.println(IPUtil.checkIPs(ips));
String[] illlegalIps = {"127.100.19", "127.0.0.1"}; String[] illlegalIps = {"127.100.19", "127.0.0.1"};
System.err.println(AddressServerParamCheckUtil.checkIps(illlegalIps)); System.err.println(IPUtil.checkIPs(illlegalIps));
} }
} }

View File

@ -30,6 +30,7 @@ import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.common.utils.ThreadUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -87,9 +88,9 @@ public class ServerListManager implements Closeable {
this.isStarted = true; this.isStarted = true;
List<String> serverAddrs = new ArrayList<String>(); List<String> serverAddrs = new ArrayList<String>();
for (String serverAddr : fixed) { for (String serverAddr : fixed) {
String[] serverAddrArr = serverAddr.split(":"); String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) { if (serverAddrArr.length == 1) {
serverAddrs.add(serverAddrArr[0] + ":" + ParamUtil.getDefaultServerPort()); serverAddrs.add(serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else { } else {
serverAddrs.add(serverAddr); serverAddrs.add(serverAddr);
} }
@ -156,9 +157,10 @@ public class ServerListManager implements Closeable {
if (serverAddr.startsWith(HTTPS) || serverAddr.startsWith(HTTP)) { if (serverAddr.startsWith(HTTPS) || serverAddr.startsWith(HTTP)) {
serverAddrs.add(serverAddr); serverAddrs.add(serverAddr);
} else { } else {
String[] serverAddrArr = serverAddr.split(":"); String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) { if (serverAddrArr.length == 1) {
serverAddrs.add(HTTP + serverAddrArr[0] + ":" + ParamUtil.getDefaultServerPort()); serverAddrs.add(HTTP + serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil
.getDefaultServerPort());
} else { } else {
serverAddrs.add(HTTP + serverAddr); serverAddrs.add(HTTP + serverAddr);
} }
@ -355,10 +357,10 @@ public class ServerListManager implements Closeable {
List<String> result = new ArrayList<String>(lines.size()); List<String> result = new ArrayList<String>(lines.size());
for (String serverAddr : lines) { for (String serverAddr : lines) {
if (StringUtils.isNotBlank(serverAddr)) { if (StringUtils.isNotBlank(serverAddr)) {
String[] ipPort = serverAddr.trim().split(":"); String[] ipPort = IPUtil.splitIPPortStr(serverAddr.trim());
String ip = ipPort[0].trim(); String ip = ipPort[0].trim();
if (ipPort.length == 1) { if (ipPort.length == 1) {
result.add(ip + ":" + ParamUtil.getDefaultServerPort()); result.add(ip + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else { } else {
result.add(serverAddr); result.add(serverAddr);
} }

View File

@ -17,7 +17,7 @@
package com.alibaba.nacos.client.config.utils; package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.IpUtils; import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import java.util.List; import java.util.List;
@ -190,7 +190,7 @@ public class ParamUtils {
} }
String[] ipsArr = betaIps.split(","); String[] ipsArr = betaIps.split(",");
for (String ip : ipsArr) { for (String ip : ipsArr) {
if (!IpUtils.isIpv4(ip)) { if (!IPUtil.isIP(ip)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "betaIps invalid"); throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "betaIps invalid");
} }
} }

View File

@ -45,6 +45,7 @@ import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.utils.HttpMethod; import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.common.utils.ThreadUtils;
@ -588,8 +589,8 @@ public class NamingProxy implements Closeable {
if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) { if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) {
url = curServer + api; url = curServer + api;
} else { } else {
if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) { if (!IPUtil.containsPort(curServer)) {
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER + serverPort; curServer = curServer + IPUtil.IP_PORT_SPLITER + serverPort;
} }
url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api; url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
} }

View File

@ -51,8 +51,6 @@ public class UtilAndComs {
public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level";
public static final String SERVER_ADDR_IP_SPLITER = ":";
public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT = public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT =
Runtime.getRuntime().availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1; Runtime.getRuntime().availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1;

View File

@ -16,7 +16,7 @@
package com.alibaba.nacos.common.tls; package com.alibaba.nacos.common.tls;
import com.alibaba.nacos.common.utils.IpUtils; import com.alibaba.nacos.common.utils.IPUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,7 +38,7 @@ public final class SelfHostnameVerifier implements HostnameVerifier {
private static ConcurrentHashMap<String, Boolean> hosts = new ConcurrentHashMap<String, Boolean>(); private static ConcurrentHashMap<String, Boolean> hosts = new ConcurrentHashMap<String, Boolean>();
private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", "127.0.0.1"}; private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", IPUtil.localHostIP()};
public SelfHostnameVerifier(HostnameVerifier hv) { public SelfHostnameVerifier(HostnameVerifier hv) {
this.hv = hv; this.hv = hv;
@ -49,22 +49,22 @@ public final class SelfHostnameVerifier implements HostnameVerifier {
if (LOCALHOST_HOSTNAME[0].equalsIgnoreCase(hostname) || LOCALHOST_HOSTNAME[1].equals(hostname)) { if (LOCALHOST_HOSTNAME[0].equalsIgnoreCase(hostname) || LOCALHOST_HOSTNAME[1].equals(hostname)) {
return true; return true;
} }
if (isIpv4(hostname)) { if (isIP(hostname)) {
return true; return true;
} }
return hv.verify(hostname, session); return hv.verify(hostname, session);
} }
private static boolean isIpv4(String host) { private static boolean isIP(String host) {
if (host == null || host.isEmpty()) { if (host == null || host.isEmpty()) {
LOGGER.warn("host is empty, isIPv4 = false"); LOGGER.warn("host is empty, isIP = false");
return false; return false;
} }
Boolean cacheHostVerify = hosts.get(host); Boolean cacheHostVerify = hosts.get(host);
if (cacheHostVerify != null) { if (cacheHostVerify != null) {
return cacheHostVerify; return cacheHostVerify;
} }
boolean isIp = IpUtils.isIpv4(host); boolean isIp = IPUtil.isIP(host);
hosts.putIfAbsent(host, isIp); hosts.putIfAbsent(host, isIp);
return isIp; return isIp;
} }

View File

@ -0,0 +1,222 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ip tool.
*
* @author Nacos
*/
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName", "PMD.ClassNamingShouldBeCamelRule"})
public class IPUtil {
public static final boolean PREFER_IPV6_ADDRESSES = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses"));
public static final String IPV6_START_MARK = "[";
public static final String IPV6_END_MARK = "]";
public static final String ILLEGAL_IP_PREFIX = "illegal ip: ";
public static final String IP_PORT_SPLITER = ":";
public static final int SPLIT_IP_PORT_RESULT_LENGTH = 2;
public static final String PERCENT_SIGN_IN_IPV6 = "%";
private static final String LOCAL_HOST_IP_V4 = "127.0.0.1";
private static final String LOCAL_HOST_IP_V6 = "[::1]";
private static Pattern ipv4Pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
private static final int IPV4_ADDRESS_LENGTH = 4;
private static final int IPV6_ADDRESS_LENGTH = 16;
private static final String CHECK_OK = "ok";
/**
* get localhost ip.
* @return java.lang.String
*/
public static String localHostIP() {
if (PREFER_IPV6_ADDRESSES) {
return LOCAL_HOST_IP_V6;
}
return LOCAL_HOST_IP_V4;
}
/**
* check whether the ip address is IPv4.
*
* @param addr ip address
* @return boolean
*/
public static boolean isIPv4(String addr) {
try {
return InetAddress.getByName(addr).getAddress().length == IPV4_ADDRESS_LENGTH;
} catch (UnknownHostException e) {
return false;
}
}
/**
* check whether the ip address is IPv6.
*
* @param addr ip address
* @return boolean
*/
public static boolean isIPv6(String addr) {
try {
return InetAddress.getByName(addr).getAddress().length == IPV6_ADDRESS_LENGTH;
} catch (UnknownHostException e) {
return false;
}
}
/**
* check whether the str is ip address (IPv4 or IPv6).
*
* @param addr ip address str
* @return boolean
*/
public static boolean isIP(String addr) {
try {
InetAddress.getByName(addr);
return true;
} catch (UnknownHostException e) {
return false;
}
}
/**
* Check if the address contains a port.
* 2020/9/3 14:53
* @param address address string
* @return boolean
*/
public static boolean containsPort(String address) {
return splitIPPortStr(address).length == SPLIT_IP_PORT_RESULT_LENGTH;
}
/**
* Split IP and port strings, support IPv4 and IPv6, IP in IPv6 must be enclosed with [].
*
* @param str ip and port string
* @return java.lang.String[]
*/
public static String[] splitIPPortStr(String str) {
if (StringUtils.isBlank(str)) {
throw new IllegalArgumentException("ip and port string cannot be empty!");
}
String[] serverAddrArr;
if (str.startsWith(IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
if (str.endsWith(IPV6_END_MARK)) {
serverAddrArr = new String[1];
serverAddrArr[0] = str;
} else {
serverAddrArr = new String[2];
serverAddrArr[0] = str.substring(0, (str.indexOf(IPV6_END_MARK) + 1));
serverAddrArr[1] = str.substring((str.indexOf(IPV6_END_MARK) + 2));
}
if (!isIPv6(serverAddrArr[0])) {
throw new IllegalArgumentException("The IPv6 address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
} else {
serverAddrArr = str.split(":");
if (serverAddrArr.length > SPLIT_IP_PORT_RESULT_LENGTH) {
throw new IllegalArgumentException("The IP address(\"" + str
+ "\") is incorrect. If it is an IPv6 address, please use [] to enclose the IP part!");
}
if (!isIPv4(serverAddrArr[0])) {
throw new IllegalArgumentException("The IPv4 address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
}
return serverAddrArr;
}
/**
* Resolve the IP from the string containing the IP address.
* @param str string containing IP address
* @return java.lang.String
*/
public static String getIPFromString(String str) {
if (StringUtils.isBlank(str)) {
return "";
}
String result = "";
if (StringUtils.containsIgnoreCase(str, IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
result = str.substring(str.indexOf(IPV6_START_MARK), (str.indexOf(IPV6_END_MARK) + 1));
if (!isIPv6(result)) {
result = "";
}
} else {
Matcher m = ipv4Pattern.matcher(str);
if (m.find()) {
result = m.group();
if (!isIPv4(result)) {
result = "";
}
}
}
return result;
}
/**
* Check ips.
*
* @param ips ips
* @return 'ok' if check passed, otherwise illegal ip
*/
public static String checkIPs(String... ips) {
if (ips == null || ips.length == 0) {
return CHECK_OK;
}
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
if (IPUtil.isIP(ip)) {
continue;
}
illegalResponse.append(ip + ",");
}
if (illegalResponse.length() == 0) {
return CHECK_OK;
}
return ILLEGAL_IP_PREFIX + illegalResponse.substring(0, illegalResponse.length() - 1);
}
/**
* Check whether checkIPs result is "ok".
* @param checkIPsResult checkIPs result
* @return boolean
*/
public static boolean checkOK(String checkIPsResult) {
return CHECK_OK.equals(checkIPsResult);
}
}

View File

@ -1,49 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ip tool.
*
* @author Nacos
*/
public class IpUtils {
private static final Pattern IPV4_PATTERN = Pattern
.compile("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$");
private static final Pattern IPV6_PATTERN = Pattern.compile("^([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$");
public static boolean isIpv4(String addr) {
return isMatch(addr, IPV4_PATTERN);
}
public static boolean isIpv6(String addr) {
return isMatch(addr, IPV6_PATTERN);
}
private static boolean isMatch(String data, Pattern pattern) {
if (StringUtils.isBlank(data)) {
return false;
}
Matcher mat = pattern.matcher(data);
return mat.find();
}
}

View File

@ -0,0 +1,120 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.utils;
import org.junit.Assert;
import org.junit.Test;
/**
* test IpUtil.
* @ClassName: IpUtilTest
* @date 2020/9/3 10:31
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class IPUtilTest {
@Test
public void testIsIPv4() {
Assert.assertTrue(IPUtil.isIPv4("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv4("[::1]"));
Assert.assertFalse(IPUtil.isIPv4("asdfasf"));
Assert.assertFalse(IPUtil.isIPv4("ffgertert"));
}
@Test
public void testIsIPv6() {
Assert.assertTrue(IPUtil.isIPv6("[::1]"));
Assert.assertFalse(IPUtil.isIPv6("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv6("er34234"));
}
@Test
public void testIsIP() {
Assert.assertTrue(IPUtil.isIP("[::1]"));
Assert.assertTrue(IPUtil.isIP("127.0.0.1"));
Assert.assertFalse(IPUtil.isIP("er34234"));
}
@Test
public void testGetIPFromString() {
Assert.assertEquals("[::1]", IPUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("[::1]", IPUtil.getIPFromString(
"jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("127.0.0.1",
IPUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("127.0.0.1", IPUtil.getIPFromString(
"jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("",
IPUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("", IPUtil.getIPFromString(
"jdbc:mysql://[127.0.0.1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
"jdbc:mysql://666.288.333.444:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
}
@Test
public void testSplitIpPort() {
checkSplitIPPortStr("[::1]:88", false, "[::1]", "88");
checkSplitIPPortStr("[::1]", false, "[::1]");
checkSplitIPPortStr("127.0.0.1:88", false, "127.0.0.1", "88");
checkSplitIPPortStr("127.0.0.1", false, "127.0.0.1");
checkSplitIPPortStr("[2001:db8:0:0:1:0:0:1]:88", false, "[2001:db8:0:0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:0db8:0:0:1:0:0:1]:88", false, "[2001:0db8:0:0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8::1:0:0:1]:88", false, "[2001:db8::1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8::0:1:0:0:1]:88", false, "[2001:db8::0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:0db8::1:0:0:1]:88", false, "[2001:0db8::1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8:0:0:1::1]:88", false, "[2001:db8:0:0:1::1]", "88");
checkSplitIPPortStr("[2001:db8:0000:0:1::1]:88", false, "[2001:db8:0000:0:1::1]", "88");
checkSplitIPPortStr("[2001:DB8:0:0:1::1]:88", false, "[2001:DB8:0:0:1::1]", "88");
checkSplitIPPortStr("[fe80::3ce6:7132:808e:707a%19]:88", false, "[fe80::3ce6:7132:808e:707a%19]", "88");
checkSplitIPPortStr("::1:88", true);
checkSplitIPPortStr("[::1:88", true);
checkSplitIPPortStr("[127.0.0.1]:88", true);
}
/**
* checkSplitIpPortStr.
* 2020/9/4 14:12
* @param addr addr
* @param isEx isEx
* @param equalsStrs equalsStrs
*/
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
try {
String[] array = IPUtil.splitIPPortStr(addr);
Assert.assertTrue(array.length == equalsStrs.length);
if (array.length > 1) {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
Assert.assertTrue(array[1].equals(equalsStrs[1]));
} else {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
}
} catch (Exception ex) {
if (!isEx) {
// No exception is expected here, but an exception has occurred
Assert.assertTrue("Unexpected exception", false);
}
}
}
}

View File

@ -24,11 +24,10 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource; import javax.sql.DataSource;
import com.alibaba.nacos.common.utils.IPUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
@ -83,8 +82,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
private volatile int masterIndex; private volatile int masterIndex;
private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
@Override @Override
public void init() { public void init() {
queryTimeout = ConvertUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3); queryTimeout = ConvertUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
@ -190,10 +187,10 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
if (!isHealthList.get(i)) { if (!isHealthList.get(i)) {
if (i == masterIndex) { if (i == masterIndex) {
// The master is unhealthy. // The master is unhealthy.
return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getJdbcUrl()); return "DOWN:" + IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl());
} else { } else {
// The slave is unhealthy. // The slave is unhealthy.
return "WARN:" + getIpFromUrl(dataSourceList.get(i).getJdbcUrl()); return "WARN:" + IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl());
} }
} }
} }
@ -201,16 +198,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
return "UP"; return "UP";
} }
private String getIpFromUrl(String url) {
Matcher m = ipPattern.matcher(url);
if (m.find()) {
return m.group();
}
return "";
}
static String defaultIfNull(String value, String defaultValue) { static String defaultIfNull(String value, String defaultValue) {
return null == value ? defaultValue : value; return null == value ? defaultValue : value;
} }
@ -269,10 +256,10 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
} catch (DataAccessException e) { } catch (DataAccessException e) {
if (i == masterIndex) { if (i == masterIndex) {
FATAL_LOG.error("[db-error] master db {} down.", FATAL_LOG.error("[db-error] master db {} down.",
getIpFromUrl(dataSourceList.get(i).getJdbcUrl())); IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
} else { } else {
FATAL_LOG.error("[db-error] slave db {} down.", FATAL_LOG.error("[db-error] slave db {} down.",
getIpFromUrl(dataSourceList.get(i).getJdbcUrl())); IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
} }
isHealthList.set(i, Boolean.FALSE); isHealthList.set(i, Boolean.FALSE);

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.common.utils.IPUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,7 +41,7 @@ public class SystemConfig {
if (StringUtils.isNotEmpty(address)) { if (StringUtils.isNotEmpty(address)) {
return address; return address;
} else { } else {
address = "127.0.0.1"; address = IPUtil.localHostIP();
} }
try { try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

View File

@ -17,6 +17,7 @@
package com.alibaba.nacos.core.cluster; package com.alibaba.nacos.core.cluster;
import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -41,8 +42,6 @@ import java.util.stream.Collectors;
*/ */
public class MemberUtils { public class MemberUtils {
private static final String SEMICOLON = ":";
private static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused"; private static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused";
private static ServerMemberManager manager; private static ServerMemberManager manager;
@ -79,8 +78,8 @@ public class MemberUtils {
String address = member; String address = member;
int port = defaultPort; int port = defaultPort;
if (address.contains(SEMICOLON)) { String[] info = IPUtil.splitIPPortStr(address);
String[] info = address.split(SEMICOLON); if (info.length > 1) {
address = info[0]; address = info[0];
port = Integer.parseInt(info[1]); port = Integer.parseInt(info[1]);
} }

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.core.distributed.raft;
import com.alibaba.nacos.common.JustForTest; import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.LoggerUtils; import com.alibaba.nacos.common.utils.LoggerUtils;
import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.consistency.LogProcessor; import com.alibaba.nacos.consistency.LogProcessor;
@ -163,7 +164,7 @@ public class JRaftServer {
RaftExecutor.init(config); RaftExecutor.init(config);
final String self = config.getSelfMember(); final String self = config.getSelfMember();
String[] info = self.split(":"); String[] info = IPUtil.splitIPPortStr(self);
selfIp = info[0]; selfIp = info[0];
selfPort = Integer.parseInt(info[1]); selfPort = Integer.parseInt(info[1]);
localPeerId = PeerId.parsePeer(self); localPeerId = PeerId.parsePeer(self);

View File

@ -113,6 +113,13 @@ public class WebUtils {
try { try {
value = HttpUtils.decode(new String(value.getBytes(StandardCharsets.UTF_8), encoding), encoding); value = HttpUtils.decode(new String(value.getBytes(StandardCharsets.UTF_8), encoding), encoding);
} catch (UnsupportedEncodingException ignore) { } catch (UnsupportedEncodingException ignore) {
} catch (Exception ex) {
// If the value contains a special character without encoding (such as "[IPv6]"),
// a URLDecoder exception is thrown, which is ignored and the original value is returned
final String seq = "URLDecoder";
if (!StringUtils.contains(ex.toString(), seq)) {
throw ex;
}
} }
return value.trim(); return value.trim();
} }

View File

@ -0,0 +1,27 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
ALTER TABLE `config_info_tag`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;
ALTER TABLE `his_config_info`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL AFTER `src_user`;
ALTER TABLE `config_info`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;
ALTER TABLE `config_info_beta`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;

View File

@ -27,7 +27,7 @@ CREATE TABLE `config_info` (
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
`src_user` text COMMENT 'source user', `src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip', `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
`app_name` varchar(128) DEFAULT NULL, `app_name` varchar(128) DEFAULT NULL,
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
`c_desc` varchar(256) DEFAULT NULL, `c_desc` varchar(256) DEFAULT NULL,
@ -72,7 +72,7 @@ CREATE TABLE `config_info_beta` (
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
`src_user` text COMMENT 'source user', `src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip', `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`) UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
@ -94,7 +94,7 @@ CREATE TABLE `config_info_tag` (
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
`src_user` text COMMENT 'source user', `src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip', `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`) UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';
@ -150,7 +150,7 @@ CREATE TABLE `his_config_info` (
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`src_user` text, `src_user` text,
`src_ip` varchar(20) DEFAULT NULL, `src_ip` varchar(50) DEFAULT NULL,
`op_type` char(10) DEFAULT NULL, `op_type` char(10) DEFAULT NULL,
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
PRIMARY KEY (`nid`), PRIMARY KEY (`nid`),

View File

@ -27,7 +27,7 @@ CREATE TABLE config_info (
gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
src_user varchar(128) DEFAULT NULL, src_user varchar(128) DEFAULT NULL,
src_ip varchar(20) DEFAULT NULL, src_ip varchar(50) DEFAULT NULL,
c_desc varchar(256) DEFAULT NULL, c_desc varchar(256) DEFAULT NULL,
c_use varchar(64) DEFAULT NULL, c_use varchar(64) DEFAULT NULL,
effect varchar(64) DEFAULT NULL, effect varchar(64) DEFAULT NULL,
@ -52,7 +52,7 @@ CREATE TABLE his_config_info (
gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000', gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000',
gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000', gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000',
src_user varchar(128), src_user varchar(128),
src_ip varchar(20) DEFAULT NULL, src_ip varchar(50) DEFAULT NULL,
op_type char(10) DEFAULT NULL, op_type char(10) DEFAULT NULL,
constraint hisconfiginfo_nid_key PRIMARY KEY (nid)); constraint hisconfiginfo_nid_key PRIMARY KEY (nid));
@ -73,7 +73,7 @@ CREATE TABLE config_info_beta (
gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
src_user varchar(128), src_user varchar(128),
src_ip varchar(20) DEFAULT NULL, src_ip varchar(50) DEFAULT NULL,
constraint configinfobeta_id_key PRIMARY KEY (id), constraint configinfobeta_id_key PRIMARY KEY (id),
constraint uk_configinfobeta_datagrouptenant UNIQUE (data_id,group_id,tenant_id)); constraint uk_configinfobeta_datagrouptenant UNIQUE (data_id,group_id,tenant_id));
@ -89,7 +89,7 @@ CREATE TABLE config_info_tag (
gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00',
src_user varchar(128), src_user varchar(128),
src_ip varchar(20) DEFAULT NULL, src_ip varchar(50) DEFAULT NULL,
constraint configinfotag_id_key PRIMARY KEY (id), constraint configinfotag_id_key PRIMARY KEY (id),
constraint uk_configinfotag_datagrouptenanttag UNIQUE (data_id,group_id,tenant_id,tag_id)); constraint uk_configinfotag_datagrouptenanttag UNIQUE (data_id,group_id,tenant_id,tag_id));
@ -210,3 +210,19 @@ CREATE TABLE permissions (
INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE); INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);
INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN'); INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
/******************************************/
/* ipv6 support */
/******************************************/
ALTER TABLE `config_info_tag`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;
ALTER TABLE `his_config_info`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL AFTER `src_user`;
ALTER TABLE `config_info`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;
ALTER TABLE `config_info_beta`
MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`;

View File

@ -17,6 +17,7 @@
package com.alibaba.nacos.naming.cluster; package com.alibaba.nacos.naming.cluster;
import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MembersChangeEvent; import com.alibaba.nacos.core.cluster.MembersChangeEvent;
@ -125,9 +126,10 @@ public class ServerListManager extends MemberChangeListener {
continue; continue;
} }
String[] info = IPUtil.splitIPPortStr(params[1]);
Member server = Optional.ofNullable(memberManager.find(params[1])) Member server = Optional.ofNullable(memberManager.find(params[1]))
.orElse(Member.builder().ip(params[1].split(UtilsAndCommons.IP_PORT_SPLITER)[0]).state(NodeState.UP) .orElse(Member.builder().ip(info[0]).state(NodeState.UP)
.port(Integer.parseInt(params[1].split(UtilsAndCommons.IP_PORT_SPLITER)[1])).build()); .port(Integer.parseInt(info[1])).build());
server.setExtendVal(MemberMetaDataConstants.SITE_KEY, params[0]); server.setExtendVal(MemberMetaDataConstants.SITE_KEY, params[0]);
server.setExtendVal(MemberMetaDataConstants.WEIGHT, params.length == 4 ? Integer.parseInt(params[3]) : 1); server.setExtendVal(MemberMetaDataConstants.WEIGHT, params.length == 4 ? Integer.parseInt(params[3]) : 1);
@ -212,7 +214,7 @@ public class ServerListManager extends MemberChangeListener {
} }
if (allServers.size() > 0 && !ApplicationUtils.getLocalAddress() if (allServers.size() > 0 && !ApplicationUtils.getLocalAddress()
.contains(UtilsAndCommons.LOCAL_HOST_IP)) { .contains(IPUtil.localHostIP())) {
for (Member server : allServers) { for (Member server : allServers) {
if (Objects.equals(server.getAddress(), ApplicationUtils.getLocalAddress())) { if (Objects.equals(server.getAddress(), ApplicationUtils.getLocalAddress())) {
continue; continue;

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.consistency.persistent.raft; package com.alibaba.nacos.naming.consistency.persistent.raft;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.Callback;
@ -1003,8 +1004,8 @@ public class RaftCore implements Closeable {
* @return api url * @return api url
*/ */
public static String buildUrl(String ip, String api) { public static String buildUrl(String ip, String api) {
if (!ip.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(ip)) {
ip = ip + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); ip = ip + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
return "http://" + ip + ApplicationUtils.getContextPath() + api; return "http://" + ip + ApplicationUtils.getContextPath() + api;
} }

View File

@ -16,10 +16,10 @@
package com.alibaba.nacos.naming.consistency.persistent.raft; package com.alibaba.nacos.naming.consistency.persistent.raft;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.naming.misc.HttpClient; import com.alibaba.nacos.naming.misc.HttpClient;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -45,8 +45,8 @@ public class RaftProxy {
*/ */
public void proxyGet(String server, String api, Map<String, String> params) throws Exception { public void proxyGet(String server, String api, Map<String, String> params) throws Exception {
// do proxy // do proxy
if (!server.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(server)) {
server = server + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
String url = "http://" + server + ApplicationUtils.getContextPath() + api; String url = "http://" + server + ApplicationUtils.getContextPath() + api;
@ -67,8 +67,8 @@ public class RaftProxy {
*/ */
public void proxy(String server, String api, Map<String, String> params, HttpMethod method) throws Exception { public void proxy(String server, String api, Map<String, String> params, HttpMethod method) throws Exception {
// do proxy // do proxy
if (!server.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(server)) {
server = server + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
String url = "http://" + server + ApplicationUtils.getContextPath() + api; String url = "http://" + server + ApplicationUtils.getContextPath() + api;
RestResult<String> result; RestResult<String> result;
@ -103,8 +103,8 @@ public class RaftProxy {
public void proxyPostLarge(String server, String api, String content, Map<String, String> headers) public void proxyPostLarge(String server, String api, String content, Map<String, String> headers)
throws Exception { throws Exception {
// do proxy // do proxy
if (!server.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(server)) {
server = server + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
String url = "http://" + server + ApplicationUtils.getContextPath() + api; String url = "http://" + server + ApplicationUtils.getContextPath() + api;

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.healthcheck.HealthCheckStatus; import com.alibaba.nacos.naming.healthcheck.HealthCheckStatus;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
@ -60,9 +61,6 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
private String app; private String app;
private static final Pattern IP_PATTERN = Pattern
.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):?(\\d{1,5})?");
private static final Pattern ONLY_DIGIT_AND_DOT = Pattern.compile("(\\d|\\.)+"); private static final Pattern ONLY_DIGIT_AND_DOT = Pattern.compile("(\\d|\\.)+");
private static final String SPLITER = "_"; private static final String SPLITER = "_";
@ -119,19 +117,19 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
} }
String provider = ipAddressAttributes[0]; String provider = ipAddressAttributes[0];
Matcher matcher = IP_PATTERN.matcher(provider); String[] providerAddr;
if (!matcher.matches()) { try {
providerAddr = IPUtil.splitIPPortStr(provider);
} catch (Exception ex) {
return null; return null;
} }
int expectedGroupCount = 2;
int port = 0; int port = 0;
if (NumberUtils.isNumber(matcher.group(expectedGroupCount))) { if (providerAddr.length == IPUtil.SPLIT_IP_PORT_RESULT_LENGTH && NumberUtils.isNumber(providerAddr[1])) {
port = Integer.parseInt(matcher.group(expectedGroupCount)); port = Integer.parseInt(providerAddr[1]);
} }
Instance instance = new Instance(matcher.group(1), port); Instance instance = new Instance(providerAddr[0], port);
// 7 possible formats of config: // 7 possible formats of config:
// ip:port // ip:port
@ -360,8 +358,7 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
*/ */
public void validate() throws NacosException { public void validate() throws NacosException {
if (onlyContainsDigitAndDot()) { if (onlyContainsDigitAndDot()) {
Matcher matcher = IP_PATTERN.matcher(getIp() + ":" + getPort()); if (!IPUtil.containsPort(getIp() + IPUtil.IP_PORT_SPLITER + getPort())) {
if (!matcher.matches()) {
throw new NacosException(NacosException.INVALID_PARAM, throw new NacosException(NacosException.INVALID_PARAM,
"instance format invalid: Your IP address is spelled incorrectly"); "instance format invalid: Your IP address is spelled incorrectly");
} }

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.cluster.ServerMemberManager;
@ -956,8 +957,8 @@ public class ServiceManager implements RecordListener<Service> {
contained = false; contained = false;
List<Instance> instances = service.allIPs(); List<Instance> instances = service.allIPs();
for (Instance instance : instances) { for (Instance instance : instances) {
if (containedInstance.contains(":")) { if (IPUtil.containsPort(containedInstance)) {
if (StringUtils.equals(instance.getIp() + ":" + instance.getPort(), containedInstance)) { if (StringUtils.equals(instance.getIp() + IPUtil.IP_PORT_SPLITER + instance.getPort(), containedInstance)) {
contained = true; contained = true;
break; break;
} }

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.healthcheck; package com.alibaba.nacos.naming.healthcheck;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
@ -135,7 +136,7 @@ public class ClientBeatCheckTask implements Runnable {
.appendParam("ephemeral", "true").appendParam("clusterName", instance.getClusterName()) .appendParam("ephemeral", "true").appendParam("clusterName", instance.getClusterName())
.appendParam("serviceName", service.getName()).appendParam("namespaceId", service.getNamespaceId()); .appendParam("serviceName", service.getName()).appendParam("namespaceId", service.getNamespaceId());
String url = "http://127.0.0.1:" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath() String url = "http://" + IPUtil.localHostIP() + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance?" + request.toUrl(); + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance?" + request.toUrl();
// delete instance asynchronously: // delete instance asynchronously:

View File

@ -17,6 +17,7 @@
package com.alibaba.nacos.naming.misc; package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.constant.HttpHeaderConsts;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
@ -202,8 +203,8 @@ public class NamingProxy {
RestResult<String> result; RestResult<String> result;
if (!curServer.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(curServer)) {
curServer = curServer + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
result = HttpClient.httpGet("http://" + curServer + api, headers, params); result = HttpClient.httpGet("http://" + curServer + api, headers, params);
@ -244,8 +245,8 @@ public class NamingProxy {
RestResult<String> result; RestResult<String> result;
if (!curServer.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(curServer)) {
curServer = curServer + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
if (isPost) { if (isPost) {
@ -294,8 +295,8 @@ public class NamingProxy {
RestResult<String> result; RestResult<String> result;
if (!curServer.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (!IPUtil.containsPort(curServer)) {
curServer = curServer + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
} }
if (isPost) { if (isPost) {

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.misc; package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.InetUtils; import com.alibaba.nacos.sys.utils.InetUtils;
@ -32,23 +33,7 @@ public class NetUtils {
* @return local server address * @return local server address
*/ */
public static String localServer() { public static String localServer() {
return InetUtils.getSelfIP() + UtilsAndCommons.IP_PORT_SPLITER + ApplicationUtils.getPort(); return InetUtils.getSelfIP() + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
}
/**
* Transfer int to IP.
*
* @param ip ip int
* @return IP string
*/
public static String num2ip(int ip) {
int[] b = new int[4];
b[0] = (ip >> 24) & 0xff;
b[1] = (ip >> 16) & 0xff;
b[2] = (ip >> 8) & 0xff;
b[3] = ip & 0xff;
return b[0] + "." + b[1] + "." + b[2] + "." + b[3];
} }
} }

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.misc; package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
@ -45,7 +46,7 @@ public class ServerStatusSynchronizer implements Synchronizer {
String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath() String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/operator/server/status"; + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/operator/server/status";
if (serverIP.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (IPUtil.containsPort(serverIP)) {
url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/operator/server/status"; + "/operator/server/status";
} }

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.naming.misc; package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
@ -46,7 +47,7 @@ public class ServiceStatusSynchronizer implements Synchronizer {
String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath() String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service/status"; + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service/status";
if (serverIP.contains(UtilsAndCommons.IP_PORT_SPLITER)) { if (IPUtil.containsPort(serverIP)) {
url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/service/status"; + "/service/status";
} }

View File

@ -95,10 +95,6 @@ public class UtilsAndCommons {
public static final String CACHE_KEY_SPLITER = "@@@@"; public static final String CACHE_KEY_SPLITER = "@@@@";
public static final String LOCAL_HOST_IP = "127.0.0.1";
public static final String IP_PORT_SPLITER = ":";
public static final int MAX_PUBLISH_WAIT_TIME_MILLIS = 5000; public static final int MAX_PUBLISH_WAIT_TIME_MILLIS = 5000;
public static final String VERSION_STRING_SYNTAX = "[0-9]+\\.[0-9]+\\.[0-9]+"; public static final String VERSION_STRING_SYNTAX = "[0-9]+\\.[0-9]+\\.[0-9]+";

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.sys.utils;
import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.SlowEvent; import com.alibaba.nacos.common.notify.SlowEvent;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.Constants;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -25,6 +26,7 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
@ -33,8 +35,6 @@ import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.alibaba.nacos.sys.env.Constants.IP_ADDRESS; import static com.alibaba.nacos.sys.env.Constants.IP_ADDRESS;
import static com.alibaba.nacos.sys.env.Constants.NACOS_SERVER_IP; import static com.alibaba.nacos.sys.env.Constants.NACOS_SERVER_IP;
@ -51,12 +51,6 @@ public class InetUtils {
private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class); private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class);
private static final String NUM = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
private static final String IP_REGEX = "^" + NUM + "\\." + NUM + "\\." + NUM + "\\." + NUM + "$";
private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX);
private static String selfIP; private static String selfIP;
private static boolean useOnlySiteLocalInterface = false; private static boolean useOnlySiteLocalInterface = false;
@ -87,11 +81,11 @@ public class InetUtils {
if (StringUtils.isBlank(nacosIP)) { if (StringUtils.isBlank(nacosIP)) {
nacosIP = ApplicationUtils.getProperty(IP_ADDRESS); nacosIP = ApplicationUtils.getProperty(IP_ADDRESS);
} }
if (!StringUtils.isBlank(nacosIP)) {
boolean illegalIP = !StringUtils.isBlank(nacosIP) && !(isIP(nacosIP) || isDomain(nacosIP)); if (!(IPUtil.isIP(nacosIP) || isDomain(nacosIP))) {
if (illegalIP) {
throw new RuntimeException("nacos address " + nacosIP + " is not ip"); throw new RuntimeException("nacos address " + nacosIP + " is not ip");
} }
}
String tmpSelfIP = nacosIP; String tmpSelfIP = nacosIP;
if (StringUtils.isBlank(tmpSelfIP)) { if (StringUtils.isBlank(tmpSelfIP)) {
preferHostnameOverIP = Boolean.getBoolean(SYSTEM_PREFER_HOSTNAME_OVER_IP); preferHostnameOverIP = Boolean.getBoolean(SYSTEM_PREFER_HOSTNAME_OVER_IP);
@ -117,7 +111,14 @@ public class InetUtils {
tmpSelfIP = Objects.requireNonNull(findFirstNonLoopbackAddress()).getHostAddress(); tmpSelfIP = Objects.requireNonNull(findFirstNonLoopbackAddress()).getHostAddress();
} }
} }
if (IPUtil.PREFER_IPV6_ADDRESSES && !tmpSelfIP.startsWith(IPUtil.IPV6_START_MARK) && !tmpSelfIP
.endsWith(IPUtil.IPV6_END_MARK)) {
tmpSelfIP = IPUtil.IPV6_START_MARK + tmpSelfIP + IPUtil.IPV6_END_MARK;
if (StringUtils.contains(tmpSelfIP, IPUtil.PERCENT_SIGN_IN_IPV6)) {
tmpSelfIP = tmpSelfIP.substring(0, tmpSelfIP.indexOf(IPUtil.PERCENT_SIGN_IN_IPV6))
+ IPUtil.IPV6_END_MARK;
}
}
if (!Objects.equals(selfIP, tmpSelfIP) && Objects.nonNull(selfIP)) { if (!Objects.equals(selfIP, tmpSelfIP) && Objects.nonNull(selfIP)) {
IPChangeEvent event = new IPChangeEvent(); IPChangeEvent event = new IPChangeEvent();
event.setOldIP(selfIP); event.setOldIP(selfIP);
@ -159,8 +160,9 @@ public class InetUtils {
if (!ignoreInterface(ifc.getDisplayName())) { if (!ignoreInterface(ifc.getDisplayName())) {
for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) { for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) {
InetAddress address = addrs.nextElement(); InetAddress address = addrs.nextElement();
if (address instanceof Inet4Address && !address.isLoopbackAddress() && isPreferredAddress( boolean isLegalIpVersion = IPUtil.PREFER_IPV6_ADDRESSES ? address instanceof Inet6Address
address)) { : address instanceof Inet4Address;
if (isLegalIpVersion && !address.isLoopbackAddress() && isPreferredAddress(address)) {
LOG.debug("Found non-loopback interface: " + ifc.getDisplayName()); LOG.debug("Found non-loopback interface: " + ifc.getDisplayName());
result = address; result = address;
} }
@ -216,11 +218,6 @@ public class InetUtils {
return false; return false;
} }
public static boolean isIP(String str) {
Matcher matcher = IP_PATTERN.matcher(str);
return matcher.matches();
}
/** /**
* juege str is right domain. * juege str is right domain.
* *