Netty服务端:如何可靠获取客户端IP地址,即使端口动态变化?
在使用Netty构建Java服务端时,获取客户端IP地址和端口号至关重要,例如用于连接管理。然而,客户端IP保持不变,端口却每次连接都变化的情况,常常困扰开发者。本文将分析此问题,并提供解决方案。
代码示例展示了Netty服务端获取并存储客户端IP和端口的逻辑:通过channel.remoteAddress()获取客户端地址,并将其存储在remoteAddressChannelMap中。
/** * 客户端连接时执行 * 1. 打印连接信息 * 2. 存储客户端IP和连接通道到remoteAddressChannelMap */@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); System.err.println("新客户端连接:"+ channel.remoteAddress()); // 提取IP地址,忽略端口号 String clientIp = remoteAddress.getAddress().getHostAddress(); remoteAddressChannelMap.put(clientIp, channel); System.out.println("remoteAddressChannelMap size: " + remoteAddressChannelMap.size());}
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。