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

前端 未结 3 1333
野的像风
野的像风 2020-12-29 21:35

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:

<         


        
相关标签:
3条回答
  • 2020-12-29 22:17

    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();
    }
    
    0 讨论(0)
  • 2020-12-29 22:17

    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();
    }
    
    0 讨论(0)
  • 2020-12-29 22:35

    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){}
    
    0 讨论(0)
提交回复
热议问题