update: support custom gateway ip (#101)

This commit is contained in:
hongqiaowei
2021-03-31 19:02:50 +08:00
committed by GitHub
parent d89c2c4160
commit 8b6ff01a93

View File

@@ -17,6 +17,7 @@
package we.util; package we.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -41,31 +42,37 @@ public class NetworkUtils {
private static String serverIp; private static String serverIp;
private static final String SERVER_IP = "SERVER_IP";
public static String getServerIp() { public static String getServerIp() {
try { try {
if (serverIp == null) { if (serverIp == null) {
boolean found = false; serverIp = System.getenv(SERVER_IP);
Enumeration<NetworkInterface> nis = null; log.info("SERVER_IP is " + serverIp);
nis = NetworkInterface.getNetworkInterfaces(); if (StringUtils.isBlank(serverIp)) {
while (nis.hasMoreElements()) { boolean found = false;
NetworkInterface ni = (NetworkInterface) nis.nextElement(); Enumeration<NetworkInterface> nis = null;
Enumeration<InetAddress> ias = ni.getInetAddresses(); nis = NetworkInterface.getNetworkInterfaces();
while (ias.hasMoreElements()) { while (nis.hasMoreElements()) {
InetAddress ia = ias.nextElement(); NetworkInterface ni = (NetworkInterface) nis.nextElement();
if (ia.isSiteLocalAddress()) { Enumeration<InetAddress> ias = ni.getInetAddresses();
serverIp = ia.getHostAddress(); while (ias.hasMoreElements()) {
found = true; InetAddress ia = ias.nextElement();
if (ia.isSiteLocalAddress()) {
serverIp = ia.getHostAddress();
found = true;
break;
}
}
if (found) {
break; break;
} }
} }
if (found) { if (!found) {
break; InetAddress ia = InetAddress.getLocalHost();
serverIp = ia.getHostAddress();
} }
} }
if (!found) {
InetAddress ia = InetAddress.getLocalHost();
serverIp = ia.getHostAddress();
}
} }
return serverIp; return serverIp;
} catch (SocketException | UnknownHostException e) { } catch (SocketException | UnknownHostException e) {