I\'m writing a Java RESTful service hosted on Heroku based on an example -> https://api.heroku.com/myapps/template-java-jaxrs/clone
My sample service is:
<
You can inject HttpServletRequest:
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getIp(@Context HttpServletRequest req) {
String remoteHost = req.getRemoteHost();
String remoteAddr = req.getRemoteAddr();
int remotePort = req.getRemotePort();
String msg = remoteHost + " (" + remoteAddr + ":" + remotePort + ")";
return Response.ok(msg).build();
}
Based on @user647772 and @Ethan fusion. Thanks to them ;)
inject HttpServletRequest:
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getFromp(@Context HttpServletRequest req) {
String from = _getUserFrom(req);
return Response.ok(from).build();
}
private String _getUserFrom(HttpServletRequest req) {
String xForwardedFor = req.getHeader("X-Forwarded-For");
xForwardedFor = xForwardedFor != null && xForwardedFor.contains(",") ? xForwardedFor.split(",")[0]:xForwardedFor;
String remoteHost = req.getRemoteHost();
String remoteAddr = req.getRemoteAddr();
int remotePort = req.getRemotePort();
StringBuffer sb = new StringBuffer();
if (remoteHost != null
&& !"".equals(remoteHost)
&& !remoteHost.equals(remoteAddr)) {
sb.append(remoteHost).append(" ");
}
if (xForwardedFor != null
&& !"".equals(xForwardedFor)) {
sb.append(xForwardedFor).append("(fwd)=>");
}
if (remoteAddr != null || !"".equals(remoteAddr)) {
sb.append(remoteAddr).append(":").append(remotePort);
}
return sb.toString();
}
As Luke said, when using Heroku, the remote host is the AWS application tier, therefore the EC2 ip address.
"X-Forwarded-For" header is the answer:
String ip = "0.0.0.0";
try {
ip = req.getHeader("X-Forwarded-For").split(",")[0];
} catch (Exception ignored){}