Is there an easy way to get the clients IP address?

0
"How to get the computer name (can be replaced by IP address)? When updating Entity in Mendix, I want Entity to retain the terminal information "computer name" that I entered. Is there any way to get the "computer name" (or IP address) in Mendix?"
asked
4 answers
3

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.

answered
2

the community commons module has an useful Java action GetIP

https://marketplace.mendix.com/link/component/170 

answered
2

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.

answered
2

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

 

answered