Getting the user's IP in Java

Issue

How can I get the ip address of users who connect to my site located on my server using apache?
I only get the ip address of my server.

protected void  getUserIp (){
    try {
        InetAddress ia = InetAddress.getLocalHost();
        String ipAddr = ia.getHostAddress();
        String hostName = ia.getHostName();
        log.debug("Local IP: " + ipAddr + "and" + "HOST: " + hostName);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

Solution

Is this code running inside a Spring controller ?

You can add a HttpServletRequest request argument to the controller method, which Spring will inject for you, and then you can do request.getRemoteAddr()

The HttpServletRequest object is coming from the Apache Tomcat

Answered By – Omer Vertman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published