Reliable way to get client IP address in CXF JAX-WS one-way method call

amo picture amo · Jul 26, 2012 · Viewed 8.4k times · Source

I'm using following code to get client IP address for a JAX-WS one-way method call:

protected HttpServletRequest getServletRequest() {
    MessageContext ctx = wsContext.getMessageContext();
    return (HttpServletRequest) ctx.get( MessageContext.SERVLET_REQUEST );
}

protected synchronized String getClientIp() {
    String clientIp = "";
    HttpServletRequest request = getServletRequest();
    if ( request != null ) {
        clientIp = request.getRemoteAddr();

        // Handle proxy
        String header = request.getHeader( "x-forwarded-for" );
        if( header != null && !header.isEmpty() ) {
            clientIp = header.split( "," )[0];
        }
    }
    return clientIp;
}

When multiple clients connect in, the IP address retrieved for a request is occasionally an incorrect cached value from an earlier request. What is a reliable way to get the one-way call originator's IP address?

Answer

user1687299 picture user1687299 · Sep 20, 2012

you can use the follow code snippet to finding the client IP

Message message = PhaseInterceptorChain.getCurrentMessage();
HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
request.getRemoteAddr()