eolivelli commented on a change in pull request #2240: fix the problem that the
method InetAddress.getLocalHost().getHostAddress() gets ip as 127.0.0.1
URL: https://github.com/apache/bookkeeper/pull/2240#discussion_r369247197
##########
File path:
bookkeeper-server/src/main/java/org/apache/bookkeeper/net/NetUtils.java
##########
@@ -85,4 +86,44 @@ public static String
resolveNetworkLocation(DNSToSwitchMapping dnsResolver, Inet
return rNames.get(0);
}
+ public static String getLocalHost() throws UnknownHostException {
+ String ip = InetAddress.getLocalHost().getHostAddress();
+ if (ip.equals("127.0.0.1")) {
+ return getAddress();
+ } else
+ return ip;
+
+ }
+
+ private static boolean isboolIp(String ipAddress) {
+ Pattern pattern = Pattern.compile(ip);
+ Matcher matcher = pattern.matcher(ipAddress);
+ return matcher.matches();
+ }
+
+ private static String getAddress() throws UnknownHostException {
+ try {
+ for (Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
+ NetworkInterface networkInterface = interfaces.nextElement();
+ if (networkInterface.isLoopback() ||
networkInterface.isVirtual() || !networkInterface.isUp()) {
+ continue;
+ }
+ Enumeration<InetAddress> addresses =
networkInterface.getInetAddresses();
+ if (addresses.hasMoreElements()) {
+ while (addresses.hasMoreElements()) {
+ String ip = addresses.nextElement().getHostAddress();
+ if (isboolIp(ip)) {
+ return ip;
+ }
+ }
+ }
+ }
+ throw new RuntimeException("InetAddress
java.net.InetAddress.getLocalHost() throws UnknownHostException");
+ } catch (Throwable e) {
Review comment:
Please catch only specific exceptions
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services