5

I need to know the clients ip addresses, Here is my cod

    public static void main(String[] args) throws Exception {
    server = HttpServer.create(new InetSocketAddress(8000), 0);
    server.createContext("/", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
    System.out.println("Client ip is: " + server.getAddress().getAddress());
}

handler:

    public static class MyHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange t) throws IOException {

    t.getRemoteAddress().getAddress(); // t is 0:0:0:0:0:0:0:
    }
}

Result: Client ip is: /0:0:0:0:0:0:0:0

Why i cant get real clients ip?

2 Answers2

2

Generally you can use servletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your web-app. But, if user is behind a proxy server or access your web server through a load balancer (for example, in cloud hosting), the above code snippet will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

Hence you should should get the IP address of the request’s HTTP header “X-Forwarded-For (XFF)“

 String ipAddress = request.getHeader("X-FORWARDED-FOR");  
   if (ipAddress == null) {  
       ipAddress = request.getRemoteAddr();  
   }

This snippet is taken from here, as the explanation is best and needs no editing. For more elaborate solution you can refer to answers to this question . Especially the one by user- basZero.

Community
  • 1
  • 1
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
  • Should i refuse using of `HttpServer` and start coding with `HttpServletRequest` and `HttpServletResponse` Objects? –  Aug 13 '14 at 11:32
-2
InetAddress address = server.getAddress().getAddress();
System.out.println("Client ip is: " +  address.getHostAddress());

This code above should give you the address. If you still get 0s for the IP, then there could be some permission issues.

Ali
  • 1