Netty Socket 获取 Nginx TCP 代理真实 IP
在使用 Netty Socket 和 Nginx TCP 代理时,可以通过以下步骤获取真实 IP:
- 在 Nginx 配置文件中添加以下配置:
stream {
upstream backend {
server your_netty_socket_ip:your_netty_socket_port;
}
server {
listen your_nginx_tcp_proxy_port;
proxy_pass backend;
proxy_protocol on;
}
}
其中,your_netty_socket_ip 和 your_netty_socket_port 分别为 Netty Socket 服务器的 IP 地址和端口号,your_nginx_tcp_proxy_port 为 Nginx TCP 代理的端口号。
- 在 Netty Socket 服务器中获取真实 IP:
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
pipeline.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
HttpHeaders headers = request.headers();
String ip = headers.get('X-Forwarded-For');
// ip 即为真实 IP
}
// ...
}
// ...
});
在 Netty Socket 服务器中,通过 X-Forwarded-For 获取真实 IP。Nginx 在代理请求时会添加 X-Forwarded-For 头部,其中包含了客户端的真实 IP。通过该头部即可获取真实 IP。
原文地址: https://www.cveoy.top/t/topic/m8zD 著作权归作者所有。请勿转载和采集!