33import org .slf4j .Logger ;
44import org .slf4j .LoggerFactory ;
55
6+ import java .net .InetAddress ;
67import java .net .NetworkInterface ;
8+ import java .util .Collections ;
79
810/**
911 * Environment utility class.
@@ -13,19 +15,26 @@ public class EnvUtils {
1315 private static final Logger LOG = LoggerFactory .getLogger (EnvUtils .class );
1416
1517 /**
16- * Returns the local host name or address.
18+ * Returns the local host name or IP address. Can be used to set {@code Referer} HTTP header.
19+ * If fails to find the local host name or address, returns an empty string.
1720 * @param returnAddress if true, return address; otherwise, return name
1821 * @return string representing the local host name or address
1922 */
2023 public static String getLocalhostNameOrAddress (final boolean returnAddress ) {
2124 try {
2225
23- return NetworkInterface .networkInterfaces ()
24- .flatMap (NetworkInterface ::inetAddresses )
25- .filter (ia -> !ia .isLoopbackAddress ())
26- .findFirst ()
27- .map (ia -> returnAddress ? ia .getHostAddress () : ia .getCanonicalHostName ())
28- .orElse ("" );
26+ for (NetworkInterface networkInterface : Collections .list (NetworkInterface .getNetworkInterfaces ())) {
27+ for (InetAddress inetAddress : Collections .list (networkInterface .getInetAddresses ())) {
28+ if (inetAddress .isLoopbackAddress ()) {
29+ continue ;
30+ }
31+ if (returnAddress ) {
32+ return inetAddress .getHostAddress ();
33+ } else {
34+ return inetAddress .getCanonicalHostName ();
35+ }
36+ }
37+ }
2938 } catch (Exception e ) {
3039 LOG .error ("Failed to get local host name or address" , e );
3140 }
0 commit comments