In a custom java action
// BEGIN EXTRA CODE
private String getClientIp() {
IContext ctx = getContext();
Optional<IMxRuntimeRequest> orr = ctx.getRuntimeRequest();
String realIP = null;
if (orr.isPresent()) {
IMxRuntimeRequest rr = orr.get();
HttpServletRequest request = rr.getHttpServletRequest();
realIP = rr.getHeader("X-Real-IP");
if( realIP == null )
realIP = rr.getHeader("X-Forwarded-For");
if( realIP == null )
realIP = rr.getRemoteAddr();
}
return realIP;
}
// END EXTRA CODE
I think I copied this from some other question on this forum.
the community commons module has an useful Java action GetIP
The GetIP java action is included in the "Http Commons” module.
Looks like this module has not been updated since 2018 and is still a Mx 7 module, so you need to open it in Mx 8.12-8.18 first I guess.
Following on from Edwin and Ilya’s answers, I use this code in a Java action. It was essentially just lifted from Http Commons when we needed it in a Mx8 project. The action just needs to return a String.
// BEGIN USER CODE
IContext ctx = this.getContext();
if (ctx.getRuntimeRequest().isPresent()) {
IMxRuntimeRequest req = ctx.getRuntimeRequest().get();
// https://stackoverflow.com/questions/16558869/getting-ip-address-of-client
String xForwardedForHeader = req.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return req.getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client,
// proxy1, proxy2 ...
// we only want the client
String forwardIp = new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
boolean validIP = checkIP(forwardIp);
if (validIP) {
return forwardIp;
} else {
Core.getLogger("GetIP").error("Could not parse X-Forwarded-for header to an IP address. Header: "+forwardIp);
return "";
}
}
} else {
return "";
}
// END USER CODE