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

北慕城南 提交于 2019-12-03 01:08:08

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

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!