0

I am starting a WebService inside a JavaSE application and I want to get the client's caller IP. Is that possible?

I have written a small test case:

import java.net.InetSocketAddress;
import java.util.concurrent.*;
import javax.jws.*;
import javax.xml.ws.Endpoint;
import com.sun.net.httpserver.*;

@WebService
public class TestWs {
   @WebMethod public String testMethod(String param) {
      String clientHostIp = ""; // how to obtain client's host ?
      return "hello "+ clientHostIp;
   }
   public static void main(String[] args) throws Exception {
      ExecutorService executorService = Executors.newFixedThreadPool(2);
      HttpServer thttpserver = HttpServer.create(new InetSocketAddress("0.0.0.0", 2000),8);
      final HttpServer httpserver = thttpserver;
      httpserver.setExecutor(executorService);
      httpserver.start();
      HttpContext ctx = httpserver.createContext("/TestWs");
      final Endpoint wsendpoint = Endpoint.create(new TestWs());
      wsendpoint.publish(ctx);
   }
}
David Hofmann
  • 5,683
  • 12
  • 50
  • 78
  • 1
    See http://stackoverflow.com/questions/12727989/jax-ws-getting-client-ip Note this limitation: if your app server is behind a web or proxy server, the IP will most likely be the IP of that host, not the actual client. – Devon_C_Miller Mar 26 '14 at 22:00

1 Answers1

0

This post helped my fix my issue, but it ties my code to internal sun API :(

import java.net.InetSocketAddress; 
import java.util.concurrent.*;
import javax.annotation.Resource;
import javax.jws.*;
import javax.xml.ws.*;
import com.sun.net.httpserver.*;
import com.sun.xml.internal.ws.developer.JAXWSProperties;

@WebService
public class TestWs {

   @Resource
   private WebServiceContext wsc;

   @WebMethod public String testMethod(String param) {
      HttpExchange exchange = (HttpExchange) wsc.getMessageContext().get(JAXWSProperties.HTTP_EXCHANGE);
      return "hello "+ exchange.getRemoteAddress().getHostString();
   }

   public static void main(String[] args) throws Exception {
      ExecutorService executorService = Executors.newFixedThreadPool(2);
      HttpServer thttpserver = HttpServer.create(new InetSocketAddress("0.0.0.0", 2000), 8);
      final HttpServer httpserver = thttpserver;
      httpserver.setExecutor(executorService);
      httpserver.start();
      HttpContext ctx = httpserver.createContext("/TestWs");
      final Endpoint wsendpoint = Endpoint.create(new TestWs());
      wsendpoint.publish(ctx);
   }
}
Community
  • 1
  • 1
David Hofmann
  • 5,683
  • 12
  • 50
  • 78