How to get the IP address when a session is created?

fabien7474 picture fabien7474 · Aug 30, 2010 · Viewed 20.6k times · Source

In my grails application, I have implemented the interface HttpSessionListener to listen for session creation as given below:

class MyHttpSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        log.info "***************** Session created: id= ${event.getSession()?.id}"
    }
}

Now, I would like to log the IP address that is responsible for the session creation.

How can I do that?

Answer

Aaron Saunders picture Aaron Saunders · Aug 30, 2010

you can access the RequestContextHolder and get the value

String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
           .getRequest().getRemoteAddr();