Retrieve user IP address from EventListener in an osgi plugin

I have an osgi plugin in which I have EventListeners. When i recieve an event (LoginEvent for example) I would like to retrieve the user’s (remote) IP address. I’ve tried ExecutingHttpRequest.get().getRemoteAddr() but get NPE. I believe get() is returning null.
Any pointers?

That’s how I work it myself -

def req = ExecutingHttpRequest?.get()
if(req) {
    def ip = req.getHeader("X-Forwarded-For")
    def hostname = req.getHeader("X-Forwarded-Client-Hostname")

    issue.setCustomFieldValue(ipField, ip)
    issue.setCustomFieldValue(hnField, hostname)
}

Be careful since ip is pii and in today’s env that might not be an awesome thing to have…

That said - if there’s an associated Http Request - you can inject HttpContext:
https://docs.atlassian.com/sal-api/2.12.1/sal-api/apidocs/com/atlassian/sal/api/web/context/HttpContext.html

And get hold of the request object that way. However I should point out that getRemoteAddr() may in some cases return the remote ip address. I would use the X-Forwarded headers if they’re set in before using RemoteAddr. Also be aware that Confluence(I think) has rolled out ipv6 support.

1 Like

Thanks for responding! But how exactly would I do that?
What I have is an EventListener, so I’m in a method being triggered, for example:

    @EventListener
    public void onLoginEvent(LoginEvent event) {
        String remote = getRemoteAddress(); // how?
        // ....        
    }

Inject the dependency HttpContext and then use the getRequest() method.