Getting the IP Address Of A client For a webservice
Asked Answered
D

4

20

I am using JAX-WS and I am having trouble retrieving the client information that is consuming a webservice. I've found out how to do it with JAX-RPC, and Apache Tomcat Axis, but not with JAX-WS. Does anyone have an idea about this?

Dariodariole answered 29/10, 2009 at 4:17 Comment(0)
L
50

What about this:

@WebService
public class MyService {

  @Resource
  WebServiceContext wsContext; 

  /**
   * Web service operation
   */ 
  @WebMethod 
  public String myMethod() { 

    MessageContext mc = wsContext.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST); 
    System.out.println("Client IP = " + req.getRemoteAddr()); 

  }

} 
Limonene answered 29/10, 2009 at 4:30 Comment(4)
I think I just missed the @Resource annotation.Dariodariole
To the best of my knowledge this is the best description of how to do this on the whole wide web. ;) Thank you, Pascal!Pirn
I try same but mc size 22 and "request" is null. I can't understand why, have you any idea?Moratorium
This works only in a servlet container but the OP asked for a JAX-WS implementation. Take a look at this posting for a good summary to retrieve the IP address in different environments.Hesse
M
5

Or this:

@Path("terminal")
public class terminal {
    @Context private javax.servlet.http.HttpServletRequest hsr;
    @GET
    @Path("get_ip")
    @Produces("text/plain")
    public String get_ip()
    {
            return ip = hsr.getRemoteAddr();
    }
}
Marieann answered 14/12, 2010 at 7:54 Comment(1)
Is this not applicable to REST only?Malachite
W
3

Taking a huge and appreciated hint from Zayin and Darren's answer/edit, I tried this, and it works too.

@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("ip")
public String sayIP(@Context HttpServletRequest req, @QueryParam("p1") String p1, ...) {
    return req.getRemoteAddr();
}
Welltodo answered 6/6, 2012 at 2:7 Comment(0)
F
0
public String getIp(@Context HttpServletRequest req) {
    return req.getRemoteHost();
}
Febrifacient answered 29/10, 2013 at 5:35 Comment(2)
@Context cannot be identified, and no import is suggested, what is this exactly ?Doyledoyley
@united-expression, jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/core/…, jersey.java.net/documentation/latest/jaxrs-resources.htmlFebrifacient

© 2022 - 2024 — McMap. All rights reserved.