Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out incoming RESTful request's IP using JAX-RS on Heroku?

People also ask

Is JAX-RS part of Java EE?

The latest version is JAX-RS 2.0 [JSR 339], which was released as part of the Java EE 7 platform.

What is your understanding about JAX-RS in Java?

JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013.


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();
}

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){}

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();
}