提交 5658558a authored 作者: Thomas Mueller's avatar Thomas Mueller

Connections from a local address other than 'localhost' were not allowed.

上级 a97687c0
...@@ -24,8 +24,11 @@ import org.h2.security.SecureSocketFactory; ...@@ -24,8 +24,11 @@ import org.h2.security.SecureSocketFactory;
*/ */
public class NetUtils { public class NetUtils {
private static final int CACHE_MILLIS = 1000;
private static InetAddress bindAddress; private static InetAddress bindAddress;
private static String cachedLocalAddress;
private static long cachedLocalAddressTime;
private NetUtils() { private NetUtils() {
// utility class // utility class
} }
...@@ -141,22 +144,29 @@ public class NetUtils { ...@@ -141,22 +144,29 @@ public class NetUtils {
} }
/** /**
* Check if a socket is connected to localhost. * Check if a socket is connected to a local address.
* *
* @param socket the socket * @param socket the socket
* @return true if it is * @return true if it is
*/ */
public static boolean isLoopbackAddress(Socket socket) { public static boolean isLocalAddress(Socket socket) throws UnknownHostException {
InetAddress test = socket.getInetAddress();
boolean result = true; boolean result = true;
//## Java 1.4 begin ## //## Java 1.4 begin ##
result = socket.getInetAddress().isLoopbackAddress(); result = test.isLoopbackAddress();
if (result) { if (result) {
return result; return result;
} }
//## Java 1.4 end ## //## Java 1.4 end ##
String s = getLocalAddress(); InetAddress localhost = InetAddress.getLocalHost();
result = socket.getInetAddress().getHostAddress().equals(s); InetAddress[] list = InetAddress.getAllByName(localhost.getCanonicalHostName());
return result; for (int i = 0; i < list.length; i++) {
InetAddress addr = list[i];
if (test.equals(addr)) {
return true;
}
}
return false;
} }
/** /**
...@@ -178,10 +188,17 @@ public class NetUtils { ...@@ -178,10 +188,17 @@ public class NetUtils {
/** /**
* Get the local host address as a string. * Get the local host address as a string.
* For performance, the result is cached for one second.
* *
* @return the local host address * @return the local host address
*/ */
public static String getLocalAddress() { public static synchronized String getLocalAddress() {
long now = System.currentTimeMillis();
if (cachedLocalAddress != null) {
if (cachedLocalAddressTime + CACHE_MILLIS > now) {
return cachedLocalAddress;
}
}
InetAddress bind = null; InetAddress bind = null;
try { try {
bind = getBindAddress(); bind = getBindAddress();
...@@ -195,6 +212,8 @@ public class NetUtils { ...@@ -195,6 +212,8 @@ public class NetUtils {
if (address.equals("127.0.0.1")) { if (address.equals("127.0.0.1")) {
address = "localhost"; address = "localhost";
} }
cachedLocalAddress = address;
cachedLocalAddressTime = now;
return address; return address;
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论