从HttpServer获取客户端IP [英] Get client ip from HttpServer

查看:73
本文介绍了从HttpServer获取客户端IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道客户的IP地址,这是我的鳕鱼

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());
}

处理程序:

    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:
    }
}

结果:客户端ip为:/0:0:0:0:0:0:0:0:0

为什么我无法获得真正的客户IP?

Why i cant get real clients ip?

推荐答案

通常,您可以使用 servletRequest.getRemoteAddr()获取正在访问您的Web应用程序的客户端IP地址.但是,如果用户位于代理服务器后面或通过负载均衡器访问您的Web服务器(例如,在云托管中),则上述代码段将获取代理服务器或负载均衡器服务器的IP地址,而不是原始IP地址客户.

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.

因此,您应该获得请求的HTTP标头"X-Forwarded-For(XFF)"的IP地址

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();  
   }

此摘要摘录自此处,因为说明是最好的,不需要编辑.有关更详细的解决方案,您可以参考此问题的答案.尤其是用户basZero所提供的一种.

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.

这篇关于从HttpServer获取客户端IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆