Netty4.X 擷取用戶端IP

來源:互聯網
上載者:User

標籤:java   netty   netty4   網路編程   

    最近使用netty-4.0.23.Final 版本編寫服務端代碼,有個擷取用戶端代碼的小需求,以前使用servlet開發時很機械的就:

String ipAddr="0.0.0.0";if (reqest.getHeader("X-Forwarded-For") == null) {    ipAddr = reqest.getRemoteAddr(); }else{         ipAddr = req.getHeader("X-Forwarded-For");}


ps:X-Forwarded-For 是使用了代理(如nginx)會附加在HTTP頭域上的。

理解好HTTP協議基礎知識很重要這裡不陳述。

Netty提供非同步、事件驅動的網路應用程式架構和工具,用以快速開發高效能、高可靠性的網路伺服器和用戶端程式,支援多種協議,當然也支援HTTP協議。

啟動Netty服務的程式:

public void start() throws Exception {    EventLoopGroup bossGroup = new NioEventLoopGroup(1);    EventLoopGroup workerGroup = new NioEventLoopGroup();    try {         ServerBootstrap bootstrap = new ServerBootstrap();         bootstrap.option(ChannelOption.SO_BACKLOG, 1024);         bootstrap.group(bossGroup, workerGroup)                  .channel(NioServerSocketChannel.class)                  .handler(new LoggingHandler(LogLevel.INFO))                  .childHandler(new ServerHandlerInitializer());         Channel ch = bootstrap.bind(8080).sync().channel();         System.err.println("Open your web browser and navigate to "                           + ("http") + "://127.0.0.1:8080/");         ch.closeFuture().sync();        } catch (Exception e) {                e.printStackTrace();        } finally {          bossGroup.shutdownGracefully();          workerGroup.shutdownGracefully();        } } public class ServerHandlerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel channel) throws Exception {ChannelPipeline p = channel.pipeline();p.addLast(new HttpRequestDecoder());p.addLast(new HttpResponseEncoder());p.addLast(new ServerHandler());}}


看出NioServerSocketChannel類的源碼可以知道是對java.nio.channels.ServerSocketChannel重新封裝,所以在擷取用戶端IP時調用remoteAddress()強轉成java.net.InetSocketAddress即可擷取。

public class ServerHandler extends SimpleChannelInboundHandler<HttpObject> {@Overridepublic void channelRead0(ChannelHandlerContext ctx, HttpObject msg)throws Exception {if (msg instanceof HttpRequest) {HttpRequest mReq = (HttpRequest) msg;String clientIP = mReq.headers().get("X-Forwarded-For");if (clientIP == null) {InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();clientIP = insocket.getAddress().getHostAddress();}}}}


這樣我們就可以擷取到用戶端的IP了。


Netty4.X 擷取用戶端IP

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.