Eatsam ul haq
Eatsam ul haq

Reputation: 347

Why InetAddress.getLoopbackAddress().getHostName() is returning a localhost

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.

Upvotes: 1

Views: 779

Answers (0)

Related Questions