1

So my problem is quite simple. I want to get the URL of current environment in my application is running. The application is deployed on linux server. The problem is when I try to get the host name for my application, I always return with the localhost while I expect it to return the URL like 10.?.?.?:8080. I am not sure if getting canonicalHostName will fix my problem. The code I have used is:

public static Map<String, Object> getCurrentHost() {
        
        Map<String, Object> map =  new HashMap<String, Object>();
        try {
            map.put("hostName", InetAddress.getLoopbackAddress().getHostName());
            map.put("hostAddress", InetAddress.getLoopbackAddress().getHostAddress());
            map.put("canonicalHostName", InetAddress.getLoopbackAddress().getCanonicalHostName());
            map.put("address", InetAddress.getLoopbackAddress().getAddress());
            map.put("localHost", InetAddress.getLocalHost());
        }catch(Exception ex) {
            LOGGER.error("Exception occured while getting Host Information and exception is: "+ ex);
        }
        
        return map;
    }

I do not want to use HttpServletRequest as I can not import it in my util class.

Summary: I want to get the URL of the environment in which my application is running. It would be perfect if that could be done by InetAddress.

Eatsam ul haq
  • 317
  • 1
  • 12
  • 2
    Because that is the name of the loopback address. You wanted `InetAddress.getLocalHost().getHostName()` – Elliott Frisch Feb 03 '22 at 07:58
  • @ElliottFrisch Thanks for your answer sir. But using `InetAddress.getLocalHost().getHostName()` in local host is returning `DESKTOP-UU4CI0H` – Eatsam ul haq Feb 03 '22 at 08:09
  • 1
    And that is your host name - this is what you wanted. You can `ping DESKTOP-UU4CI0H` and it will work for you. And dont use loopback adapter as it is always 127.0.0.x and localhost as a name. – Antoniossss Feb 03 '22 at 08:11
  • @Antoniossss Technically it can be changed by [manipulating `lo0` and `/etc/hosts`](https://askubuntu.com/a/247626/214223), but it is almost always `127.0.0.1` and `localhost`. – Elliott Frisch Feb 03 '22 at 08:27
  • 1
    @ElliottFrisch: afraid not. The actual loopback at OS level may change some, but Java `getLoopbackAddress` is hardcoded to name `localhost` and address either [127.0.0.1 for v4](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/net/Inet4AddressImpl.java#L57) or [::1 = 0:0:0:0:0:0:0:1 for v6](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/net/Inet6AddressImpl.java#L115) – dave_thompson_085 Feb 03 '22 at 10:26

0 Answers0