kirti
kirti

Reputation: 4609

How to get public ip from desktop application call to our webservice

I need to capture public ip of the system calling our api, that system is a desktop Application thats calling our rest api and I am using the following code

    @RequestMapping(value = "/api", method = RequestMethod.POST)
    public @ResponseBody JSON_Response sendMessage(@RequestBody Objectjson objjson,HttpServletRequest
            request) {

        LOG.debug("sending message via payless server");
        inputjson.setSentFrom("Message Sent From Api");
    //  inputjson.setHostip(""+request.getRemoteHost());
//I am using following to capture it
        LOG.debug("--------------------------"+request.getRemoteUser());
        LOG.debug("--------------------------"+request.getLocalAddr());
        LOG.debug("--------------------------"+request.getRemoteHost());
        LOG.debug("--------------------------"+request.getPathInfo());
        LOG.debug("--------------------------"+request.getPathTranslated());
        LOG.debug("--------------------------"+request.getRemoteUser());
        LOG.debug("--------------------------"+request.getRemoteUser());
        LOG.debug("--------------------------"+request.getRemoteUser());
        LOG.debug("--------------------------"+request.getRemoteUser());
        LOG.debug("--------------------------"+request.getRemoteUser());
        JSON_Response response = sendMessageInterface.processInput(inputjson);
        LOG.debug("sending response message " + response.getStatusDescription());

        return response;
    }

I am getting my own server ip in the ip address.If i call the rest api from postman i am getting the correct ip address.

Please let me know if you find any other way to retrieve public ip .

I am using Wildfly Server wildfly-10.1.0.Final

Upvotes: 0

Views: 401

Answers (1)

locus2k
locus2k

Reputation: 2935

This is the method that i Use to get the remote user IP address. Hope it helps

public HttpServletRequest getRequest() {
  RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
  if (attribs instanceof ServletRequestAttributes) {
    HttpServletRequest request = ((ServletRequestAttributes)attribs).getRequest();
    return request;
  }
  return null;
}

public String getClientIp() {
  String remoteAddr = "";
  HttpServletRequest request = getRequest();
  if (request != null) {
    remoteAddr = request.getHeader("X-FORWARDED-FOR");
    if (remoteAddr == null || remoteAddr.trim().isEmpty()) {
      remoteAddr = request.getRemoteAddr();
    }
  }
  return remoteAddr;
}

Upvotes: 1

Related Questions