How to get client IP

Is there any way how to get client IP address at the server (part or service) JS ?

Should be in the request object, which is an argument to the get-method in your part or page JS, if I remember correctly.

2 Likes

The request object in the controllers will have the headers with the IP address
req.headers['X-Forwarded-For'] or req.host
I made a GeoIP library that will return the location for IPv4 and IPv6 but it hasn’t been released yet. Let me know if you’d like to test it and give feedback.

1 Like

I dont have ‘X-Forwarded-For’ in the header, and as for the req.host, isnt it something different? not the client IP but the server host?

https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
14.23 Host

What should be configured to see ‘X-Forwarded-For’ ’ or ‘HTTP_CLIENT_IP’ or ‘HTTP_X_FORWARDED_FOR’ or ‘HTTP_CLIENT_IP’ or ‘REMOTE_ADDR’ or whatever )

Yeap share it, please.
Maybe you can share source codes too?

You won’t see ‘X-Forwarded-For’ when you are using XP on localhost. A live website on a production server will always have it in the request. I’ll send you a private message with how to use the lib I made, but the source code is private at the moment. We’ll try to make it public soon with the first release.

I think The x-forwarded Are only there when a proxy server like apache runs in front of XP!

I thought that there is not X-Forwarded-For because I’ve tested it all at the localhost.
So I try to test it on 2 servers (in one LAN), to luck too.

This looks like a bug. Currently it is not possible to get the client IP from the request.

The “host” property in the request object now returns the value of the “Host” header, which is the host or IP address of the server, not the client. And if the “X-Forwarded-For” header is present it returns that value instead.

So it is mixing up client and server IP, depending on the header. I suppose the idea was to return either the value of the “X-Forwarded-For” header or the client IP address.

We should add a new property “remoteAddr” to the request object, that contains the client IP. This should be fixed in 6.6.

If you need to get the client IP in the current version you have to get it in Java, creating a library for example.
And call getRemoteAddr on the contextual request, like this:

com.enonic.xp.portal.PortalRequestAccessor.get().getRawRequest().getRemoteAddr()

6 Likes

XP 6.6.0 does indeed have the IP in the request as remoteAddress. Also, the Java way to get the IP has changed in 6.6
com.enonic.xp.portal.PortalRequestAccessor.get().getRemoteAddress()

The GeoIP library will be released very soon.

Check out https://market.enonic.com/vendors/enonic/com.enonic.lib.geoip

2 Likes