Ami
Ami

Reputation: 4259

How to get Remote / Client IP address using RESTful web service in java?

I have written Rest web service in my project.The web service call may come from different machine.so i need to find out the IP address through REST webservice.

From this link request.getRemoteAddr() to use this.

But i cant use getRemoteAddr(). Because my request and response are xml format.

I have used post method in REST service.Tomcat server.I have send request as xml format.

How can i get the IP address?

Upvotes: 12

Views: 38347

Answers (3)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78589

Assuming you are using JAX-RS:

@GET
Produces("application/xlm")
public String getData(@Context HttpServletRequest request){
   String ip = request.getRemoteAddr();
}

The @Context annotation allows you to inject instances of

  • javax.ws.rs.core.HttpHeaders,
  • javax.ws.rs.core.UriInfo,
  • javax.ws.rs.core.Request,
  • javax.servlet.HttpServletRequest,
  • javax.servlet.HttpServletResponse,
  • javax.servlet.ServletConfig,
  • javax.servlet.ServletContext, and
  • javax.ws.rs.core.SecurityContext objects.

Upvotes: 35

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

Even if your request is in xml/json format, you will get Remote/client machine address using request.getRemoteAddr(); because IP Address lies in HTTP Request header.

Upvotes: 0

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

Irrespective of the format (or content type) of your request (in this case xml) The IP address is supplied with your request through which the xml payload (request) is submitted. Hence, checking with your Request is the best way.

Upvotes: 0

Related Questions